Esempio n. 1
0
        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Spectrometer spectrometer = e.Result as Spectrometer;

            if (spectrometer == currentSpectrometer)
            {
                updateStartButton(false);
            }

            // should we auto-exit?
            if (opts.autoStart && opts.scanCount > 0)
            {
                bool shutdown = true;
                lock (spectrometers)
                {
                    foreach (Spectrometer s in spectrometers)
                    {
                        SpectrometerState ss = spectrometerStates[s];
                        if (ss.scanCount < opts.scanCount)
                        {
                            shutdown = false;
                        }
                    }
                }
                if (shutdown)
                {
                    Close();
                }
            }
        }
Esempio n. 2
0
        ////////////////////////////////////////////////////////////////////////
        // Business Logic
        ////////////////////////////////////////////////////////////////////////

        void initializeSpectrometer(Spectrometer s)
        {
            SpectrometerState state = new SpectrometerState(s, opts);

            // TODO: move into SpectrometerState ctor
            state.worker.DoWork             += backgroundWorker_DoWork;
            state.worker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;

            spectrometerStates.Add(s, state);

            chart1.Series.Add(state.series);

            if (!s.isARM)
            {
                s.triggerSource = TRIGGER_SOURCE.INTERNAL;
            }

            s.integrationTimeMS              = s.eeprom.minIntegrationTimeMS;
            numericUpDownIntegTimeMS.Value   = s.eeprom.minIntegrationTimeMS;
            numericUpDownIntegTimeMS.Minimum = s.eeprom.minIntegrationTimeMS;
            // numericUpDownIntegTimeMS.Maximum = s.eeprom.maxIntegrationTimeMS; // disabled to allow long integration times

            if (s.pixels > 0)
            {
                logger.info("Found {0} {1} with {2} pixels from {3:f2} to {4:f2}nm",
                            s.model, s.serialNumber, s.pixels, s.wavelengths[0], s.wavelengths[s.wavelengths.Length - 1]);
            }
            else
            {
                logger.error("Found [model: {0}] [serial: {1}] with {2} pixels", s.model, s.serialNumber, s.pixels);
            }

            // default to high-resolution laser power
            s.laserPowerResolution = Spectrometer.LaserPowerResolution.LASER_POWER_RESOLUTION_1000;
        }
 /// <summary>
 /// <see cref=" Spectrometer"/>
 /// 当扣除背景选项选中后,扣除背景。测量过程先测背景,后测原始光谱。
 /// </summary>
 /// <param name="spectrometer">Spectrometer handle</param>
 /// <param name="currentCircle">当前循环(Circles)次数</param>
 /// <returns>本次测量的数组,长度等于CCD横向(Horizontal)长度</returns>
 private double[] IsBackgroundSubtracted(Spectrometer spectrometer,int currentCircle)
 {
     double[] tempdark = new double[pixelHoriNum];
     double[] tempSpec = new double[pixelHoriNum];
     if (radioButtonSubtract.Checked&&radioButtonInSitu.Checked==false)//扣除背景
     {
         spectrometer.laserEnabled = false;
         System.Threading.Monitor.Enter(this);
         tempdark = spectrometer.getSpectrum();//背景光测量
         System.Threading.Monitor.Exit(this);
         spectrometer.laserEnabled = true;
         numericUpDownLaserPerc.Value = numericUpDownLaserPerc.Value;
         if(radioButtonPreflashOn.Checked&&radioButtonPreflashOff.Checked==false)
             IsPreflash(currentCircle);
         System.Threading.Monitor.Enter(this);
         tempSpec = spectrometer.getSpectrum();
         System.Threading.Monitor.Exit(this);
         for (int i = 0; i < pixelHoriNum; i++)
         {
             tempSpec[i] -= tempdark[i];
         }
     }
     else//不扣除背景
     {
         spectrometer.laserEnabled = true;
         numericUpDownLaserPerc.Value = numericUpDownLaserPerc.Value;
         if (radioButtonPreflashOn.Checked && radioButtonPreflashOff.Checked == false)
             IsPreflash(currentCircle);
         tempSpec = spectrometer.getSpectrum();
     }
     return tempSpec;
 }
 /// <summary>
 /// 初始化光谱仪参数
 /// </summary>
 private void InitSpectrometer()
 {
     s=driverClass.SelectSpectrometer(Driver.getInstance());//最后一个spectrometer
     this.comboBoxSpec.Text = s.model+" "+s.serialNumber;
     SpectrometerClassRead(s);
     EEPROMClassRead(eEPROM);
 }
Esempio n. 5
0
 public SpectrometerState(Spectrometer s, Options options)
 {
     spectrometer                      = s;
     opts                              = options;
     series.Name                       = s.serialNumber;
     series.ChartType                  = SeriesChartType.Line;
     worker.WorkerReportsProgress      = false;
     worker.WorkerSupportsCancellation = true;
 }
Esempio n. 6
0
        public void update(Spectrometer spec)
        {
            if (spec == null)
            {
                return;
            }

            updateFast(spec);
        }
Esempio n. 7
0
        private void comboBoxSpectrometer_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = comboBoxSpectrometer.SelectedIndex;

            if (index >= 0 && index < spectrometers.Count)
            {
                currentSpectrometer = spectrometers[index];
                updateCurrentSpectrometer();
            }
        }
 private void SpectrometerClassRead(Spectrometer s)
 {
     tecStatus = s.detectorTECEnabled;
     double detectorTECSetpointDegC = s.detectorTECSetpointDegC;
     if (!s.hasLaser)
     {
         laserStatus = false;
     }     
     else
         excitationWavelengthNM = s.excitationWavelengthNM;
     integrationTimeMS = s.integrationTimeMS;
     eEPROM = s.eeprom;
 }
Esempio n. 9
0
        /////////////////////////////////////////////////////////////////////////
        // private methods
        /////////////////////////////////////////////////////////////////////////

        internal EEPROM(Spectrometer spec)
        {
            spectrometer = spec;

            wavecalCoeffs      = new float[4];
            degCToDACCoeffs    = new float[3];
            adcToDegCCoeffs    = new float[3];
            ROIVertRegionStart = new ushort[3];
            ROIVertRegionEnd   = new ushort[3];
            badPixels          = new short[15];
            linearityCoeffs    = new float[5];
            laserPowerCoeffs   = new float[4];

            badPixelList = new List <short>();
            badPixelSet  = new SortedSet <short>();
        }
Esempio n. 10
0
        ////////////////////////////////////////////////////////////////////////
        // Background Worker: Acquisition Threads
        ////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Perform all acquisitions in background threads so the GUI stays responsive.
        /// </summary>
        /// <remarks>
        /// Note that this method is used by potentially several different
        /// BackgroundWorkers in parallel (one per attached spectrometer).
        ///
        /// TODO: rename backgroundWorkerAcquisition
        /// </remarks>
        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            Spectrometer      spectrometer = (Spectrometer)e.Argument;
            SpectrometerState state        = spectrometerStates[spectrometer];

            string prefix = String.Format("Worker.{0}.{1}", spectrometer.model, spectrometer.serialNumber);

            state.running = true;

            BackgroundWorker worker = sender as BackgroundWorker;

            while (true)
            {
                // end thread if we've been asked to cancel
                if (worker.CancellationPending)
                {
                    break;
                }

                // logger.debug("workerAcquisition: getting spectrum");
                double[] raw = spectrometer.getSpectrum();
                if (raw == null)
                {
                    Thread.Sleep(100);
                    continue;
                }

                // process for graphing
                lock (spectrometers)
                    state.processSpectrum(raw);

                // end thread if we've completed our allocated acquisitions
                if (opts.scanCount > 0 && state.scanCount >= opts.scanCount)
                {
                    break;
                }

                int delayMS = (int)Math.Max(100, opts.scanIntervalSec * 1000);
                if (delayMS > 0)
                {
                    Thread.Sleep(delayMS);
                }
            }

            state.running = false;
            e.Result      = spectrometer; // pass spectrometer handle to _Completed callback
        }
Esempio n. 11
0
        public Spectrometer SelectSpectrometer(Driver driver)
        {
            int specNum = driver.openAllSpectrometers();

            if (driver.getNumberOfSpectrometers() > 0)
            {
                for (int i = 0; i < specNum; i++)
                {
                    specInstance = driver.getSpectrometer(i);
                    spectrometers.Add(specInstance);
                }
            }
            else
            {
                throw new Exception("没有发现WasatchNET.Spectrometer实例");
            }
            return(specInstance);
        }
Esempio n. 12
0
        void update_NOT_USED <T>(string key, Spectrometer spec, MyDelegate <T> func)
        {
            logger.debug("update: directly getting {0} from {1}", key, func);
            T value = func();

            update(key, value);

            // Not currently using this code, but retaining if needed.  Basically,
            // testing with APITest suggested that our ARM comms may have difficulties
            // when piling lots of USB calls consecutively into a single thread; however,
            // those same calls succeeded when individually dispatched as separate events.
            // It may be we don't need to do that here because update(string, object) is
            // already calling a dispatcher with the RESULT of the USB call, even though
            // the USB traffic itself isn't in a thread? I really don't know, but keeping
            // this for posterity.
            //
            // autoResetEvent.WaitOne();
            // logger.debug("update: invoking a delegate for {0}", key);
            // tv.BeginInvoke(new MethodInvoker(delegate { update(key, func()); autoResetEvent.Set(); }));
        }
Esempio n. 13
0
        private void buttonInitialize_Click(object sender, EventArgs e)
        {
            comboBoxSpectrometer.Items.Clear();
            groupBoxSpectrometers.Enabled = false;

            if (driver.openAllSpectrometers() > 0)
            {
                spectrometers.Clear();
                for (int i = 0; i < driver.getNumberOfSpectrometers(); i++)
                {
                    Spectrometer s = driver.getSpectrometer(i);
                    currentSpectrometer = s;
                    spectrometers.Add(s);
                    comboBoxSpectrometer.Items.Add(String.Format("{0} ({1})", s.model, s.serialNumber));
                    initializeSpectrometer(s);

                    if (opts.integrationTimeMS > 0)
                    {
                        s.integrationTimeMS = opts.integrationTimeMS;
                    }

                    comboBoxSpectrometer.SelectedIndex = comboBoxSpectrometer.Items.Count - 1;
                    Thread.Sleep(100);

                    buttonStart_Click(null, null);
                    Thread.Sleep(100);
                }

                buttonInitialize.Enabled      = false;
                groupBoxSpectrometers.Enabled = true;

                comboBoxSpectrometer.SelectedIndex = 0;

                // AcceptButton = buttonStart;
            }
            else
            {
                logger.info("No Wasatch Photonics spectrometers were found.");
            }
        }
Esempio n. 14
0
        ////////////////////////////////////////////////////////////////////////
        // Lifecycle
        ////////////////////////////////////////////////////////////////////////

        public ScopeViewModel()
        {
            spec        = Spectrometer.getInstance();
            appSettings = AppSettings.getInstance();

            appSettings.PropertyChanged  += handleAppSettingsChange;
            spec.PropertyChanged         += handleSpectrometerChange;
            spec.showAcquisitionProgress += showAcquisitionProgress; // closure?

            // bind closures (method calls) to each Command
            acquireCmd = new Command(() => { _ = doAcquireAsync(); });
            refreshCmd = new Command(() => { _ = doAcquireAsync(); });
            saveCmd    = new Command(() => { _ = doSave(); });
            addCmd     = new Command(() => { _ = doAdd(); });
            clearCmd   = new Command(() => { _ = doClear(); });

            xAxisOptions = new ObservableCollection <XAxisOption>()
            {
                // these names must match the fields in ChartDataPoint
                new XAxisOption()
                {
                    name = "pixel", unit = "px"
                },
                new XAxisOption()
                {
                    name = "wavelength", unit = "nm"
                },
                new XAxisOption()
                {
                    name = "wavenumber", unit = "cm⁻¹"
                }
            };
            xAxisOption = xAxisOptions[0];

            updateChart();
        }
Esempio n. 15
0
 public FPGAOptions(Spectrometer s)
 {
     spectrometer = s;
     load();
 }
Esempio n. 16
0
        ////////////////////////////////////////////////////////////////////////
        // public methods
        ////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Iterate over all discoverable Wasatch Photonics USB spectrometers,
        /// and return the number found. Individual spectrometers can then be
        /// accessed via the getSpectrometer(index) call.
        /// </summary>
        /// <returns>number of Wasatch Photonics USB spectrometers found</returns>
        public int openAllSpectrometers()
        {
            logger.debug("Wasatch.NET v{0}", Assembly.GetExecutingAssembly().GetName().Version.ToString());

            SortedDictionary <string, List <Spectrometer> > sorted = new SortedDictionary <string, List <Spectrometer> >();

            // This requires libusb-1.0.dll in the path, and generates a slew of errors like:
            // MonoUsbProfileHandle : ReleaseHandle #9
            // LibUsbDotNet.LudnMonoLibUsb.MonoUsbDevice[non - UsbEndpointBase]: MonoApiError: GetDescriptor Failed
            // LibUsbDotNet.LudnMonoLibUsb.MonoUsbDevice[non - UsbEndpointBase]: Win32Error: GetLangIDs
            //
            // UsbDevice.ForceLibUsbWinBack = true;

            // This seems to be mainly for Linux
            UsbDevice.ForceLegacyLibUsb = false;

            UsbDevice.UsbErrorEvent += OnUsbError;

            UsbRegDeviceList deviceRegistries = UsbDevice.AllDevices;

            foreach (UsbRegistry usbRegistry in deviceRegistries)
            {
                String desc = String.Format("Vid:0x{0:x4} Pid:0x{1:x4} (rev:{2}) - {3}",
                                            usbRegistry.Vid,
                                            usbRegistry.Pid,
                                            (ushort)usbRegistry.Rev,
                                            usbRegistry[SPDRP.DeviceDesc]);

                if (logger.debugEnabled())
                {
                    logger.debug("USB Registry for: {0}", desc);
                    logDevice(usbRegistry);
                }

                if (usbRegistry.Vid == 0x24aa)
                {
                    Spectrometer spectrometer = new Spectrometer(usbRegistry);
                    if (spectrometer.open())
                    {
                        // sort them by model, serial (allow duplicates for unconfigured)
                        // TODO: is there any way to deterministically sort between units
                        //       without a configured unique serial number?
                        string key = String.Format("{0}-{1}", spectrometer.eeprom.model, spectrometer.eeprom.serialNumber);
                        if (!sorted.ContainsKey(key))
                        {
                            sorted.Add(key, new List <Spectrometer>());
                        }
                        sorted[key].Add(spectrometer);
                        logger.debug("openAllSpectrometers: found key {0} ({1})", key, desc);
                    }
                    else
                    {
                        logger.error("openAllSpectrometers: failed to open {0}", desc);
                    }
                }
                else
                {
                    logger.debug("openAllSpectrometers: ignored {0}", desc);
                }
            }

            // add to final list in sorted order
            spectrometers.Clear();
            foreach (KeyValuePair <string, List <Spectrometer> > pair in sorted)
            {
                foreach (Spectrometer s in pair.Value)
                {
                    spectrometers.Add(s);
                    logger.debug("openAllSpectrometers: index {0}: {1} {2}", spectrometers.Count - 1, s.model, s.serialNumber);
                }
            }

            return(spectrometers.Count);
        }
Esempio n. 17
0
        private void initializeSpectrometer()
        {
            if (spectrometer != null && !backgroundWorkerAcquisition.IsBusy)
            {
                spectrometer.close();
                spectrometer = null;
            }

            if ((spectrometer == null || !spectrometer.isOk()) && !backgroundWorkerAcquisition.IsBusy)
            {
                logger.display("Initializing spectrometer...");
                spectrometer = new SeaBreezeSpectrometer();

                spectrometer.setLogger(logger);

                string version = spectrometer.getVersion();
                if (version != null)
                {
                    this.Text = String.Format("SeaBreeze C# Demo (Demo v{0}) (SeaBreeze v{1})",
                                              Assembly.GetExecutingAssembly().GetName().Version.ToString(),
                                              version);
                }
                else
                {
                    logger.display("Warning: can't get SeaBreeze version number");
                }

                spectrometer.open();
                if (spectrometer.isOk())
                {
                    serialNumber     = spectrometer.getSerialNumber();
                    spectrometerType = spectrometer.getSpectrometerType();
                    pixels           = spectrometer.getPixelCount();
                    wavelengths      = spectrometer.getWavelengths();
                    rawSpectrum      = new double[pixels];

                    logger.display("Successfully claimed {0} with {1} pixels", spectrometerType, pixels);

                    collectionArea = spectrometer.getCollectionArea();
                    irradCal       = spectrometer.getIrradianceCalibration();
                    if (collectionArea <= 0 || irradCal == null)
                    {
                        checkBoxEnableIrradiance.Checked = false;
                        checkBoxEnableIrradiance.Enabled = false;
                    }
                    else
                    {
                        checkBoxEnableIrradiance.Enabled = true;
                        logger.display("Irradiance Collection Area = {0} cm^2", collectionArea);
                    }

                    logger.display("Electrically dark pixel indices:");
                    edcIndices = spectrometer.getEDCIndices();
                    for (int i = 0; i < edcIndices.Length; i++)
                    {
                        logger.display("  [{0}] = {1}", i, edcIndices[i]);
                    }

                    logger.display("Non-Linearity Correction Coefficients:");
                    nlcCoeffs = spectrometer.getNLCCoeffs();
                    if (nlcCoeffs != null)
                    {
                        for (int i = 0; i < nlcCoeffs.Length; i++)
                        {
                            logger.display("  [{0}] = {1}", i, nlcCoeffs[i]);
                        }
                    }

                    // buttonSave.Enabled = true;
                    btnScan.Enabled = true;
                    Refresh();
                }
                else
                {
                    logger.display("Failed to initialize spectrometer");
                    MessageBox.Show(
                        "No usable spectrometer available",
                        "SeaBreeze",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error,
                        MessageBoxDefaultButton.Button1,
                        MessageBoxOptions.DefaultDesktopOnly,
                        false);
                }
            }
            else
            {
                logger.log("Spectrometer already initialized");
            }
        }
        // ********** Initialize the spectrometer **********

        private void InitializeButton_Click(object sender, EventArgs e)
        {
            // Debug.WriteLine($"¤¤¤¤¤¤¤¤¤¤¤¤¤ DEBUG 7 ¤¤¤¤¤¤¤¤¤¤¤¤¤");
            //Close any previously used spectrometer (in case user clicks on the button more than once)
            if (spectrometer != null)
            {
                spectrometer.Close();
            }
            // Debug.WriteLine($"¤¤¤¤¤¤¤¤¤¤¤¤¤ DEBUG 8 ¤¤¤¤¤¤¤¤¤¤¤¤¤");
            //This static method searches for devices and returns a list of driver for the available devices.
            Spectrometer[] devices = Qseries.SearchDevices();
            if (devices.Length == 0)
            {
                devices = RgbSpectrometer.SearchDevices();
            }
            if (devices.Length == 0)
            {
                devices = Qstick.SearchDevices();
            }
            //Debug.WriteLine($"¤¤¤¤¤¤¤¤¤¤¤¤¤ DEBUG 9 ¤¤¤¤¤¤¤¤¤¤¤¤¤");
            //If no device was found:
            if (devices.Length == 0)
            {
                InitStatusLabel.Text = "No spectrometer found.";
                MessageBox.Show("No spectrometer found.", "Cannot initialize spectrometer",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }

            //Otherwise, take the first device and initialize it.
            spectrometer = devices[0];
            //Debug.WriteLine($"¤¤¤¤¤¤¤¤¤¤¤¤¤ DEBUG 10 ¤¤¤¤¤¤¤¤¤¤¤¤¤");
            try
            {
                InitStatusLabel.Text = "Initializing spectrometer ...";
                statusStrip1.Update();

                spectrometer.Open();
                //Debug.WriteLine($"¤¤¤¤¤¤¤¤¤¤¤¤¤ DEBUG 11 ¤¤¤¤¤¤¤¤¤¤¤¤¤");
                //Get the wavelength of each pixel (this is not actually used in this sample code)
                double[] wavelengths = spectrometer.GetWavelengths();

                //Initialize values in GUI
                ExpTimeNumericUpDown.Value = (decimal)spectrometer.ExposureTime;
                if (spectrometer is CalibratedSpectrometer)
                {
                    SensitivityCalibrationCheckBox.Checked = (spectrometer as CalibratedSpectrometer).UseSensitivityCalibration;
                    SensitivityCalibrationCheckBox.Enabled = true;
                }
                else
                {
                    SensitivityCalibrationCheckBox.Checked = false;
                    SensitivityCalibrationCheckBox.Enabled = false;
                }
                peaksTable.RowCount = numberOfPeaks;
                // Debug.WriteLine($"¤¤¤¤¤¤¤¤¤¤¤¤¤ DEBUG 12 ¤¤¤¤¤¤¤¤¤¤¤¤¤");

                for (int i = 0; i < numberOfPeaks; i++)
                {
                    peaks.Add(new COG(0, 0, 0, 0, 0));
                    peaksTable.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 26F));
                }
                //      (spectrometer as CalibratedSpectrometer).UseExternalTrigger = true;


                for (int i = 0; i < numberOfPeaks; i++)
                {
                    //Debug.WriteLine($"¤¤¤¤¤¤¤¤¤¤¤¤¤ DEBUG 13 ¤¤¤¤¤¤¤¤¤¤¤¤¤");
                    wLeft.Add(new NumericUpDown());
                    wRight.Add(new NumericUpDown());
                    threshList.Add(new NumericUpDown());
                    labelPList.Add(new System.Windows.Forms.Label());
                    labelCOG.Add(new System.Windows.Forms.Label());


                    SetWaves(wLeft[i]);
                    wLeft[i].Name = $"waveLengthLeft {(i + 1).ToString()}";
                    peaksTable.Controls.Add(wLeft[i], 2, i);

                    SetWaves(wRight[i]);
                    wRight[i].Name = $"waveLengthRight {(i + 1).ToString()}";
                    peaksTable.Controls.Add(wRight[i], 3, i);

                    SetThres(threshList[i]);
                    threshList[i].Name = $"threshold {(i + 1).ToString()}";
                    peaksTable.Controls.Add(threshList[i], 4, i);

                    SetLabelP(labelPList[i]);
                    labelPList[i].Text = $"Peak {(i+1).ToString()}";
                    peaksTable.Controls.Add(labelPList[i], 1, i);



                    //PeakTrackBox.Controls.Add(waveLengths[i]);
                }



                for (int i = 0; i < peaks.Count; i++)
                {
                    InitPeak(peaks[i], spectrometer.WavelengthCoefficients, wLeft[i], wRight[i], threshList[i]);
                    Debug.WriteLine($"¤¤¤¤¤¤¤¤¤¤¤¤¤ DEBUG 16 ¤¤¤¤¤¤¤¤¤¤¤¤¤");
                }
                // Debug.WriteLine($"¤¤¤¤¤¤¤¤¤¤¤¤¤ DEBUG 15 ¤¤¤¤¤¤¤¤¤¤¤¤¤");
                //peak1.SetWaveCof(spectrometer.WavelengthCoefficients);
                //peak1.SetWaveLeft((float)numericUpDown1.Value);
                // peak1.SetWaveRight((float)numericUpDown2.Value);
                //peak1.SetThresholde((float)numericUpDowntr1.Value * (float)0.01);
                //peak1.waveLeft = (float)numericUpDown1.Value;
                //peak1.waveRight = (float)numericUpDown2.Value;
                //peak1.waveLeft = (float)waveLengths[0].Value;
                //peak1.waveRight = (float)waveLengths[1].Value;
                //peak1.thresholde = (float)numericUpDowntr1.Value * (float)0.01;
                // peak2.SetWaveCof(spectrometer.WavelengthCoefficients);   //the overwriting happens here.
                //peak2.SetWaveLeft((float)numericUpDown3.Value);
                // peak2.SetWaveRight((float)numericUpDown4.Value);
                //peak2.SetThresholde((float)numericUpDowntr2.Value * (float)0.01);
                // peak2.waveLeft = (float)waveLengths[2].Value;
                // peak2.waveRight = (float)waveLengths[3].Value;
                // peak2.thresholde = (float)numericUpDowntr2.Value * (float)0.01;
                Debug.WriteLine($"¤¤¤¤¤¤¤¤¤¤¤¤¤ DEBUG 17 ¤¤¤¤¤¤¤¤¤¤¤¤¤");

                InitStatusLabel.Text = "Found " + spectrometer.DetailedDeviceName;
                MessageBox.Show("Device name: " + spectrometer.ModelName + Environment.NewLine
                                + "Manufacturer: " + spectrometer.Manufacturer + Environment.NewLine
                                + "Serial number: " + spectrometer.SerialNo + Environment.NewLine
                                + "Number of pixels: " + spectrometer.PixelCount,
                                "Spectrometer found and initialized", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                spectrometer         = null;
                InitStatusLabel.Text = "Initialization error.";
                MessageBox.Show(ex.Message, "Cannot initialize spectrometer",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Queries all remaining spectrometer settings (those which are not pre-loaded
        /// for fast access from the EEPROM and FPGACompilationOptions).
        ///
        /// This can take a few seconds when errors occur, which is why we're doing it
        /// from a background thread.
        /// </summary>
        /// <param name="spec">Spectrometer from which to load the settings</param>
        public void updateAll(Spectrometer spec)
        {
            // TODO: still figuring out what's wrong with these...
            //
            // 2017-10-03 16:49:57.789:  ERROR: getCmd: failed to get GET_TRIGGER_DELAY (0xab) with index 0x0000 via DEVICE_TO_HOST (0 bytes read)
            // 2017-10-03 16:49:58.790:  ERROR: getCmd: failed to get GET_DETECTOR_TEMPERATURE_SETPOINT (0xd9) with index 0x0001 via DEVICE_TO_HOST (0 bytes read)
            // 2017-10-03 16:49:59.794:  ERROR: getCmd: failed to get GET_EXTERNAL_TRIGGER_OUTPUT (0xe1) with index 0x0000 via DEVICE_TO_HOST (0 bytes read)
            // 2017-10-03 16:50:00.798:  ERROR: getCmd: failed to get GET_ACTUAL_FRAMES (0xe4) with index 0x0000 via DEVICE_TO_HOST (0 bytes read)
            //
            // update("triggerDelay", spec.triggerDelay);
            // update("triggerOutput", spec.triggerOutput);
            // update("frame", spec.actualFrames);

            logger.debug("updateAll: calling updateFast");
            updateFast(spec);

            logger.debug("updateAll: starting long pull");

            update("detectorGain", spec.detectorGain);                          // should this be eeprom or opcode?
            update("detectorOffset", spec.detectorOffset);                      // eeprom or opcode?
            update("detectorGainOdd", spec.eeprom.detectorGainOdd);
            update("detectorOffsetOdd", spec.eeprom.detectorOffsetOdd);
            update("detectorSensingThreshold", spec.detectorSensingThreshold);
            update("detectorSensingThresholdEnabled", spec.detectorSensingThresholdEnabled);
            update("triggerSource", spec.triggerSource);
            update("firmwareRev", spec.firmwareRevision);
            update("fpgaRev", spec.fpgaRevision);
            update("integrationTimeMS", spec.integrationTimeMS);
            update("continuousAcquisition", spec.continuousAcquisitionEnable);
            update("continuousFrames", spec.continuousFrames);

            if (spec.eeprom.hasCooling)
            {
                update("detectorTemperatureDegC", spec.detectorTemperatureDegC);
                update("detectorTemperatureRaw", spec.detectorTemperatureRaw);
                update("detectorTECEnabled", spec.detectorTECEnabled);
                update("detectorTECSetpointRaw", spec.detectorTECSetpointRaw);
                update("detectorTECSetpointDegC", spec.detectorTECSetpointDegC);
            }

            if (spec.fpgaOptions.hasActualIntegTime)
            {
                update("actualIntegrationTimeUS", spec.actualIntegrationTimeUS);
            }

            if (spec.fpgaOptions.hasHorizBinning)
            {
                update("horizBinning", spec.horizontalBinning);
            }

            if (spec.fpgaOptions.hasAreaScan)
            {
                update("areaScanEnabled", spec.areaScanEnabled);
            }

            if (spec.eeprom.hasLaser && spec.fpgaOptions.laserType != FPGA_LASER_TYPE.NONE)
            {
                update("laserInterlock", spec.laserInterlockEnabled);
                update("laserEnabled", spec.laserEnabled);
                update("laserModDuration", spec.laserModulationDuration);
                update("laserModEnabled", spec.laserModulationEnabled);
                update("laserModLinkedToIntegrationTime", spec.laserModulationLinkedToIntegrationTime);
                update("laserModPeriod", spec.laserModulationPeriod);
                update("laserModPulseDelay", spec.laserModulationPulseDelay);
                update("laserModPulseWidth", spec.laserModulationPulseWidth);
                update("laserRampingEnabled", spec.laserRampingEnabled);
                update("laserTemperatureSetpointRaw", spec.laserTemperatureSetpointRaw);
                update("laserTemperatureRaw", spec.laserTemperatureRaw);
                update("laserTemperatureDegC", spec.laserTemperatureDegC);
                update("adcSelection", spec.selectedADC);
            }

            if (spec.eeprom.hasBattery)
            {
                update("batteryPercentage", spec.batteryPercentage);
                update("batteryCharging", spec.batteryCharging);
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Update the TreeView with all those parameters which are cached in memory for high-speed access.
        /// </summary>
        /// <param name="spec">The spectrometer whose settings to render on the TreeView</param>
        void updateFast(Spectrometer spec)
        {
            if (spec == null)
            {
                return;
            }

            update("activePixelsHoriz", spec.eeprom.activePixelsHoriz);
            update("activePixelsVert", spec.eeprom.activePixelsVert);
            update("actualPixelsHoriz", spec.eeprom.actualPixelsHoriz);
            update("baudRate", spec.eeprom.baudRate);
            update("calibrationBy", spec.eeprom.calibrationBy);
            update("calibrationDate", spec.eeprom.calibrationDate);
            update("detector", spec.eeprom.detectorName);
            update("detectorTempMax", spec.eeprom.detectorTempMax);
            update("detectorTempMin", spec.eeprom.detectorTempMin);
            update("excitationNM", spec.excitationWavelengthNM);
            update("featureBoardType", spec.featureIdentification.boardType);
            update("featureDesc", spec.featureIdentification.firmwareDesc);
            update("VID", string.Format("0x{0:x4}", spec.featureIdentification.vid));
            update("PID", string.Format("0x{0:x4}", spec.featureIdentification.pid));
            update("fpgaDataHeader", spec.fpgaOptions.dataHeader);
            update("fpgaHasActualIntegTime", spec.fpgaOptions.hasActualIntegTime);
            update("fpgaHasAreaScan", spec.fpgaOptions.hasAreaScan);
            update("fpgaHasCFSelect", spec.fpgaOptions.hasCFSelect);
            update("fpgaHasHorizBinning", spec.fpgaOptions.hasHorizBinning);
            update("fpgaIntegrationTimeResolution", spec.fpgaOptions.integrationTimeResolution);
            update("fpgaLaserControl", spec.fpgaOptions.laserControl);
            update("fpgaLaserType", spec.fpgaOptions.laserType);
            update("hasBattery", spec.eeprom.hasBattery);
            update("hasCooling", spec.eeprom.hasCooling);
            update("hasLaser", spec.eeprom.hasLaser);
            update("maxIntegrationTimeMS", spec.eeprom.maxIntegrationTimeMS);
            update("minIntegrationTimeMS", spec.eeprom.minIntegrationTimeMS);
            update("model", spec.model);
            update("ROIHorizEnd", spec.eeprom.ROIHorizEnd);
            update("ROIHorizStart", spec.eeprom.ROIHorizStart);
            update("serialNumber", spec.serialNumber);
            update("slitSizeUM", spec.eeprom.slitSizeUM);
            update("thermistorBeta", spec.eeprom.thermistorResistanceAt298K);
            update("thermistorResistanceAt298K", spec.eeprom.thermistorResistanceAt298K);
            update("userText", spec.eeprom.userText);
            update("maxLaserPowerMW", spec.eeprom.maxLaserPowerMW);
            update("minLaserPowerMW", spec.eeprom.minLaserPowerMW);
            update("productConfiguration", spec.eeprom.productConfiguration);

            // arrays
            for (int i = 0; i < spec.eeprom.wavecalCoeffs.Length; i++)
            {
                update("wavecalCoeff" + i, spec.eeprom.wavecalCoeffs[i]);
            }
            for (int i = 0; i < spec.eeprom.degCToDACCoeffs.Length; i++)
            {
                update("degCToDACCoeff" + i, spec.eeprom.degCToDACCoeffs[i]);
            }
            for (int i = 0; i < spec.eeprom.adcToDegCCoeffs.Length; i++)
            {
                update("adcToDegCCoeff" + i, spec.eeprom.adcToDegCCoeffs[i]);
            }
            for (int i = 0; i < spec.eeprom.ROIVertRegionStart.Length; i++)
            {
                update(String.Format("ROIVertRegion{0}Start", i + 1), spec.eeprom.ROIVertRegionStart[i]);
            }
            for (int i = 0; i < spec.eeprom.ROIVertRegionEnd.Length; i++)
            {
                update(String.Format("ROIVertRegion{0}End", i + 1), spec.eeprom.ROIVertRegionEnd[i]);
            }
            for (int i = 0; i < spec.eeprom.linearityCoeffs.Length; i++)
            {
                update("linearityCoeff" + i, spec.eeprom.linearityCoeffs[i]);
            }
            for (int i = 0; i < spec.eeprom.badPixels.Length; i++)
            {
                update("badPixels" + i, spec.eeprom.badPixels[i] == -1 ? "" : spec.eeprom.badPixels[i].ToString());
            }
            for (int i = 0; i < spec.eeprom.laserPowerCoeffs.Length; i++)
            {
                update("laserPowerCoeff" + i, spec.eeprom.laserPowerCoeffs[i]);
            }
        }
 public SpectrometerState(Spectrometer spec)
 {
     this.spec = spec;
     status    = new SpectrometerStatus(spec);
     metrics   = new Metrics(this);
 }
        private void InitSpectrometer()
        {
            //Close any previously used spectrometer (in case user clicks on the button more than once)
            if (spectrometer != null)
            {
                spectrometer.Close();
            }

            //This static method searches for devices and returns a list of driver for the available devices.
            Spectrometer[] devices = Qseries.SearchDevices();
            if (devices.Length == 0)
            {
                devices = RgbSpectrometer.SearchDevices();
            }
            if (devices.Length == 0)
            {
                devices = Qstick.SearchDevices();
            }

            //If no device was found:
            if (devices.Length == 0)
            {
                InitStatusLabel.Text = "No spectrometer found.";
                MessageBox.Show("No spectrometer found.", "Cannot initialize spectrometer",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            //Otherwise, take the first device and initialize it.
            spectrometer = devices[0];
            try
            {
                InitStatusLabel.Text = "Initializing spectrometer ...";
                statusStrip1.Update();

                spectrometer.Open();

                //Get the wavelength of each pixel (this is not actually used in this sample code)
                double[] wavelengths = spectrometer.GetWavelengths();

                //Initialize values in GUI
                ExpTimeNumericUpDown.Value = (decimal)spectrometer.ExposureTime;
                if (spectrometer is CalibratedSpectrometer)
                {
                    SensitivityCalibrationCheckBox.Checked = (spectrometer as CalibratedSpectrometer).UseSensitivityCalibration;
                    SensitivityCalibrationCheckBox.Enabled = true;
                    //checkBoxEksternTrigger.Checked = (spectrometer as CalibratedSpectrometer).UseExternalTrigger;
                }
                else
                {
                    SensitivityCalibrationCheckBox.Checked = false;
                    SensitivityCalibrationCheckBox.Enabled = false;
                }

                //      (spectrometer as CalibratedSpectrometer).UseExternalTrigger = true;


                peak1.SetWaveCof(spectrometer.WavelengthCoefficients);
                peak1.SetWaveLeft((float)numericUpDown1.Value);
                peak1.SetWaveRight((float)numericUpDown2.Value);
                peak1.SetThresholde((float)numericUpDowntr1.Value * (float)0.01);


                peak2.SetWaveCof(spectrometer.WavelengthCoefficients);  //overwrite doesnt happen here
                peak2.SetWaveLeft((float)numericUpDown3.Value);
                peak2.SetWaveRight((float)numericUpDown4.Value);
                peak2.SetThresholde((float)numericUpDowntr2.Value * (float)0.01);

                Debug.WriteLine($"WAVES PEAK 1 ------------ {numericUpDown1.Value} {numericUpDown2.Value}");
                Debug.WriteLine($"WAVES PEAK 2 ------------ {numericUpDown3.Value} {numericUpDown4.Value}");


                /*
                 * InitStatusLabel.Text = "Found " + spectrometer.DetailedDeviceName;
                 * MessageBox.Show("Device name: " + spectrometer.ModelName + Environment.NewLine
                 + "Manufacturer: " + spectrometer.Manufacturer + Environment.NewLine
                 + "Serial number: " + spectrometer.SerialNo + Environment.NewLine
                 + "Number of pixels: " + spectrometer.PixelCount,
                 +     "Spectrometer found and initialized", MessageBoxButtons.OK, MessageBoxIcon.Information);
                 */
            }
            catch (Exception ex)
            {
                spectrometer         = null;
                InitStatusLabel.Text = "Initialization error.";
                MessageBox.Show(ex.Message, "Cannot initialize spectrometer",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /* private void numericUpDown2_ValueChanged(object sender, EventArgs e)
         *   {
         *   //peak1.SetWaveRight((float)numericUpDown2.Value);
         *   peak1.waveRight = (float)numericUpDown2.Value;
         *   }
         * private void numericUpDown3_ValueChanged(object sender, EventArgs e)
         *   {
         *   peak2.waveLeft = (float)numericUpDown3.Value;
         *   }
         *
         * private void numericUpDown4_ValueChanged(object sender, EventArgs e)
         *   {
         *   //peak2.SetWaveRight((float)numericUpDown4.Value);
         *   peak1.waveRight = (float)numericUpDown4.Value;
         *
         *   }
         * private void numericUpDown5_ValueChanged(object sender, EventArgs e)
         *   {
         *   //peaks[2].SetWaveLeft((float)numericUpDown5.Value);
         *   }
         * private void numericUpDown6_ValueChanged(object sender, EventArgs e)
         *   {
         *   //peaks[2].SetWaveRight((float)numericUpDown6.Value);
         *   }
         * private void numericUpDown7_ValueChanged(object sender, EventArgs e)
         *   {
         *   // peaks[3].SetWaveLeft((float)numericUpDown7.Value);
         *   }
         * private void numericUpDown8_ValueChanged(object sender, EventArgs e)
         *   {
         *   //peaks[3].SetWaveRight((float)numericUpDown8.Value);
         *
         *   }
         * private void numericUpDown9_ValueChanged(object sender, EventArgs e)
         *   {
         *   //peaks[4].SetWaveLeft((float)numericUpDown9.Value);
         *   }
         * private void numericUpDown10_ValueChanged(object sender, EventArgs e)
         *   {
         *   // peaks[4].SetWaveRight((float)numericUpDown10.Value);
         *   }
         *
         */
        private void InitSpectrometer()
        {
            //Close any previously used spectrometer (in case user clicks on the button more than once)
            if (spectrometer != null)
            {
                spectrometer.Close();
            }

            //This static method searches for devices and returns a list of driver for the available devices.
            Spectrometer[] devices = Qseries.SearchDevices();
            if (devices.Length == 0)
            {
                devices = RgbSpectrometer.SearchDevices();
            }
            if (devices.Length == 0)
            {
                devices = Qstick.SearchDevices();
            }

            //If no device was found:
            if (devices.Length == 0)
            {
                InitStatusLabel.Text = "No spectrometer found.";
                MessageBox.Show("No spectrometer found.", "Cannot initialize spectrometer",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            //Otherwise, take the first device and initialize it.
            spectrometer = devices[0];
            try
            {
                InitStatusLabel.Text = "Initializing spectrometer ...";
                statusStrip1.Update();

                spectrometer.Open();

                //Get the wavelength of each pixel (this is not actually used in this sample code)
                double[] wavelengths = spectrometer.GetWavelengths();

                //Initialize values in GUI
                ExpTimeNumericUpDown.Value = (decimal)spectrometer.ExposureTime;
                if (spectrometer is CalibratedSpectrometer)
                {
                    SensitivityCalibrationCheckBox.Checked = (spectrometer as CalibratedSpectrometer).UseSensitivityCalibration;
                    SensitivityCalibrationCheckBox.Enabled = true;
                    //checkBoxEksternTrigger.Checked = (spectrometer as CalibratedSpectrometer).UseExternalTrigger;
                }
                else
                {
                    SensitivityCalibrationCheckBox.Checked = false;
                    SensitivityCalibrationCheckBox.Enabled = false;
                }

                //      (spectrometer as CalibratedSpectrometer).UseExternalTrigger = true;
            }
            catch (Exception ex)
            {
                spectrometer         = null;
                InitStatusLabel.Text = "Initialization error.";
                MessageBox.Show(ex.Message, "Cannot initialize spectrometer",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 24
0
        void performExtraReads(Spectrometer spec)
        {
            const int EXTRA_READ_TYPES = 41;

            for (int i = 0; i < args.extraReads; i++)
            {
                int type = -1;
                if (forceExtraReadSequence == null)
                {
                    type = r.Next(EXTRA_READ_TYPES);
                }
                else
                {
                    type = forceExtraReadSequence[forceExtraReadIndex++ % forceExtraReadSequence.Length];
                }
                logger.debug("performing extraRead {0} ({1} of {2})", type, i + 1, args.extraReads);
                switch (type)
                {
                case  0: logger.debug("extraRead: actualFrames = {0}", spec.actualFrames); break;

                case  1: logger.debug("extraRead: actualIntegrationTimeUS = {0}", spec.actualIntegrationTimeUS); break;

                case  2: logger.debug("extraRead: primaryADC = 0x{0:x4}", spec.primaryADC); break;

                case  3: logger.debug("extraRead: secondaryADC = 0x{0:x4}", spec.secondaryADC); break;

                case  4: logger.debug("extraRead: batteryCharging = {0}", spec.batteryCharging); break;

                case  5: logger.debug("extraRead: batteryPercentage = {0}", spec.batteryPercentage); break;

                case  6: logger.debug("extraRead: continuousAcquisitionEnable = {0}", spec.continuousAcquisitionEnable); break;

                case  7: logger.debug("extraRead: continuousFrames = {0}", spec.continuousFrames); break;

                case  8: logger.debug("extraRead: detectorGain = {0:f2}", spec.detectorGain); break;

                case  9: logger.debug("extraRead: detectorOffset = {0}", spec.detectorOffset); break;

                case 10: logger.debug("extraRead: detectorSensingThreshold = {0}", spec.detectorSensingThreshold); break;

                case 11: logger.debug("extraRead: detectorSensingThresholdEnabled = {0}", spec.detectorSensingThresholdEnabled); break;

                case 12: logger.debug("extraRead: detectorTECEnabled = {0}", spec.detectorTECEnabled); break;

                case 13: logger.debug("extraRead: detectorTECSetpointRaw = 0x{0:x4}", spec.detectorTECSetpointRaw); break;

                case 14: logger.debug("extraRead: firmwareRevision = {0}", spec.firmwareRevision); break;

                case 15: logger.debug("extraRead: fpgaRevision = {0}", spec.fpgaRevision); break;

                case 16: logger.debug("extraRead: highGainModeEnabled = {0}", spec.highGainModeEnabled); break;

                case 17: logger.debug("extraRead: horizontalBinning = {0}", spec.horizontalBinning); break;

                case 18: logger.debug("extraRead: integrationTimeMS = {0}", spec.integrationTimeMS); break;

                case 19: logger.debug("extraRead: laserEnabled = {0}", spec.laserEnabled); break;

                case 20: logger.debug("extraRead: laserModulationEnabled = {0}", spec.laserModulationEnabled); break;

                case 21: logger.debug("extraRead: laserInterlockEnabled = {0}", spec.laserInterlockEnabled); break;

                case 22: logger.debug("extraRead: laserModulationLinkedToIntegrationTime = {0}", spec.laserModulationLinkedToIntegrationTime); break;

                case 23: logger.debug("extraRead: laserModulationPulseDelay = {0}", spec.laserModulationPulseDelay); break;

                case 24: logger.debug("extraRead: laserModulationPulseWidth = {0}", spec.laserModulationPulseWidth); break;

                case 25: logger.debug("extraRead: laserModulationDuration = {0}", spec.laserModulationDuration); break;

                case 26: logger.debug("extraRead: laserModulationPeriod = {0}", spec.laserModulationPeriod); break;

                case 27: logger.debug("extraRead: laserTemperatureDegC = {0}", spec.laserTemperatureDegC); break;

                case 28: logger.debug("extraRead: laserTemperatureSetpointRaw = {0}", spec.laserTemperatureSetpointRaw); break;

                case 29: logger.debug("extraRead: lineLength = {0}", spec.lineLength); break;

                case 30: logger.debug("extraRead: optAreaScan = {0}", spec.optAreaScan); break;

                case 31: logger.debug("extraRead: optActualIntegrationTime = {0}", spec.optActualIntegrationTime); break;

                case 32: logger.debug("extraRead: optCFSelect = {0}", spec.optCFSelect); break;

                case 33: logger.debug("extraRead: optDataHeaderTag = {0}", spec.optDataHeaderTag); break;

                case 34: logger.debug("extraRead: optHorizontalBinning = {0}", spec.optHorizontalBinning); break;

                case 35: logger.debug("extraRead: optIntegrationTimeResolution = {0}", spec.optIntegrationTimeResolution); break;

                case 36: logger.debug("extraRead: optLaserControl = {0}", spec.optLaserControl); break;

                case 37: logger.debug("extraRead: optLaserType = {0}", spec.optLaserType); break;

                case 38: logger.debug("extraRead: triggerSource = {0}", spec.triggerSource); break;

                case 39: logger.debug("extraRead: triggerOutput = {0}", spec.triggerOutput); break;

                case 40: logger.debug("extraRead: triggerDelay = {0}", spec.triggerDelay); break;

                default: break;
                }
            }
        }