def connect_spectrometer(self): if self.spec is None: devices = sb.list_devices() self.spec = sb.Spectrometer(devices[0]) self.ui.status_textBrowser.append( "Ocean Optics Device Connected!\n\n Device:\n\n" + str(sb.list_devices()[0])) else: self.ui.status_textBrowser.append("Already Connected")
def reset(self): ''' This function resets the spectrometer. To make a hardware reset unplug it from the computer and then plug in again. ''' devices = sb.list_devices() if len(sb.list_devices()) == 0: print ("No spectrometer is detected!") return else: self.Handle.close() self.Handle = sb.Spectrometer(devices[0]) self.clear()
def reset(self): ''' This function resets the spectrometer. To make a hardware reset unplug it from the computer and then plug in again. ''' devices = sb.list_devices() if len(sb.list_devices()) == 0: print("No spectrometer is detected!") return else: self.Handle.close() self.Handle = sb.Spectrometer(devices[0]) self.clear()
def __init__(self): if len(sb.list_devices()) == 0: print ("No spectrometer is detected!") return else: devices = sb.list_devices() self.Handle = sb.Spectrometer(devices[0]) print (devices) print ('Serial number:%s' % self.Handle.serial_number) print ('Model:%s' % self.Handle.model) print ('minimum_integration_time_micros: %s microseconds' % self.Handle.minimum_integration_time_micros) self.clear()
def __init__(self): if len(sb.list_devices()) == 0: print("No spectrometer is detected!") return else: devices = sb.list_devices() self.Handle = sb.Spectrometer(devices[0]) print(devices) print('Serial number:%s' % self.Handle.serial_number) print('Model:%s' % self.Handle.model) print('minimum_integration_time_micros: %s microseconds' % self.Handle.minimum_integration_time_micros) self.clear()
def __init__(self): try: sb.list_devices() if len(sb.list_devices()) == 0: print ("No spectrometer is detected! \n") self.Error = 1 return else: self.detect() except Exception, e: if (e.message == 'This should not have happened. Apparently this device has 0 serial number features. The code expects it to have 1 and only 1. Please file a bug report including a description of your device.'): #print ('Please unplug the spectrometer and then plug again. Then close the python command line and reopen it. Last') print ('Unplug the spectrometer and then plug again, then close the python command line and reopen it.') self.Error = 1 return
def animate(frameno, inttime, monitor, prefix): devices = sb.list_devices() spec = sb.Spectrometer(devices[0]) spec_model = spec._dev._model spec.integration_time_micros(inttime) x = spec.wavelengths() y = spec.intensities() line.set_ydata(y) # update the data ax.set_ylim([min(y[10:]), max(y) * 1.1]) spec.close() if not monitor: a = np.column_stack([x, y]) #in np.savetext, using inttime/1000 since the USB2000 uses microseconds, not milliseconds. if prefix: filepref = prefix else: filepref = "spectrum_data" np.savetxt("{}_{}.csv".format(filepref, frameno), a, delimiter=',', header="wavelength,intensity", fmt='%.14f', comments="#model: {0}\n#integration time: {1} ms\n".format( spec_model, inttime / 1000)) return line,
def getSpec(typ, intgTime, wl): devices = sb.list_devices() if not len(devices): print("Error: No OceanOptic Device found") sys.exit(1) for device in devices: print(device) print("getting spectrum") spec = sb.Spectrometer(devices[0]) print("setting integration time to " + str(intgTime)) spec.integration_time_micros(intgTime) """ print("getting wavelengths") rawWavelengths = spec.wavelengths() print("getting intensities") rawIntensities = spec.intensities(correct_dark_counts=False, correct_nonlinearity=False) """ spektrum = spec.spectrum() print("closing Spectroscope") spec.close() if typ == 0: writePlotSpec(spektrum, True) elif typ == 1: showWavelength(spektrum, wl)
def detect(self): try: devices = sb.list_devices() sb.Spectrometer(devices[0]).close() self.Handle = sb.Spectrometer(devices[0]) self.Error = 0 print(devices) print('Serial number:%s' % self.Handle.serial_number) print('Model:%s' % self.Handle.model) print('minimum_integration_time_micros: %s microseconds' % self.Handle.minimum_integration_time_micros) self.clear() self.Error = 0 return except Exception, e: if (e.message == 'Device already opened.'): #print ('Device will be reseted') #self.reset() print('Error: ' + e.message) print('Unplug the spectrometer and then plug again') elif (e.message == 'Error: Data transfer error'): print('Error: ' + e.message) print( 'Please unplug the spectrometer and then plug again. Then close the python command line and reopen it.' ) #return else: print(e.message) print( 'Please unplug the spectrometer and then plug again. Then close the python command line and reopen it. ' ) #return self.Error = 1 print('Openning spectrometer failed!') return
def __init__(self): # global variables that may or may not be used later on self.stopped = True self.ptrn = 0 # get spectrometer going self.devices = sb.list_devices() self.spec = sb.Spectrometer(self.devices[0]) self.spec.integration_time_micros(100000) # initial real and dummy spectra self.xs = self.spec.wavelengths() self.ys = self.spec.intensities() self.xs_roi = np.zeros(300) self.ys_roi = np.zeros(300) self.timer = QtCore.QTimer() # pressure calculation parameters # lambda zero (ref) is 694.260 based on Ragan et al JAP 72, 5539 (1992) at 295K self.alpha = 1885 self.beta = 11.0 self.lambda_0_ref = 694.260 self.lambda_0_user = 694.260 self.lambda_0_t_user = 694.260 self.lambda_r1 = 694.260 self.temperature = 295 self.pressure = 0.00
def __init__(self): # super(CoreData, self).__init__() # self.curve = gui.pw.plot() self.vline = pg.InfiniteLine(pos=694.260, angle=90.0, movable=True) gui.pw.addItem(self.vline) self.stopped = True self.ptrn = 0 self.devices = sb.list_devices() self.spec = sb.Spectrometer(self.devices[0]) self.spec.integration_time_micros(10000) self.xs = self.spec.wavelengths() self.ys = self.spec.intensities() self.xs_roi = np.zeros(300) self.ys_roi = np.zeros(300) self.timer = QtCore.QTimer() # pressure calculation parameters # lambda zero (ref) is 694.260 based on Ragan et al JAP 72, 5539 (1992) at 295K self.alpha = 1904 self.beta = 9.5 self.lambda_0_ref = 694.260 self.lambda_0_user = 694.260 self.lambda_0_t_user = 694.260 self.lambda_r1 = 694.260 self.temperature = 295 self.pressure = 0.00
def detect(self): try: devices = sb.list_devices() sb.Spectrometer(devices[0]).close() self.Handle = sb.Spectrometer(devices[0]) self.Error = 0 print (devices) print ('Serial number:%s' % self.Handle.serial_number) print ('Model:%s' % self.Handle.model) print ('minimum_integration_time_micros: %s microseconds' % self.Handle.minimum_integration_time_micros) self.clear() self.Error = 0 return except Exception, e: if (e.message == 'Device already opened.'): #print ('Device will be reseted') #self.reset() print ('Error: ' + e.message) print ('Unplug the spectrometer and then plug again') elif (e.message == 'Error: Data transfer error'): print ('Error: ' + e.message) print ('Please unplug the spectrometer and then plug again. Then close the python command line and reopen it.') #return else: print (e.message) print ('Please unplug the spectrometer and then plug again. Then close the python command line and reopen it. ') #return self.Error = 1 print('Openning spectrometer failed!') return
def test_crash_may_not_influence_following_tests(backendlified_serial): devices = list(list_devices()) if len(devices) == 0: pytest.skip("no supported device connected") _ = Spectrometer.from_serial_number(backendlified_serial) raise Exception("crash on purpose")
def test_device_cleanup_on_exit(backendlify): """test if opened devices cleanup correctly""" usb_backend = "" try: devices = list_devices() if len(devices) == 0: pytest.skip("no supported device connected") else: if psb and isinstance(devices[0], psb.SeaBreezeDevice): # noinspection PyProtectedMember usb_backend = "_pyusb_backend='{}'".format( devices[0]._raw_device.pyusb_backend) del devices finally: # noinspection PyProtectedMember list_devices._api.shutdown() # noinspection PyProtectedMember backend_name = backendlify._backend_ cmd = [ "python", "-c", "import seabreeze.%s as sb; d = sb.SeaBreezeAPI(%s).list_devices()[0]; d.open()" % (backend_name, usb_backend), ] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() assert p.returncode == 0, stderr
def __init__(self): # super(CoreData, self).__init__() self.curve = gui.pw.plot() self.stopped = True self.ptrn = 0 self.devices = sb.list_devices() self.spec = sb.Spectrometer(self.devices[0]) self.spec.integration_time_micros(10000) self.xs = self.spec.wavelengths() self.ys = self.spec.intensities() self.timer = QtCore.QTimer() # pressure calculation parameters # lambda zero (ref) is 694.260 based on Ragan et al JAP 72, 5539 (1992) at 295K self.alpha = 1904 self.beta = 9.5 self.lambda_0_ref = 694.260 self.lambda_0_user = 694.260 self.lambda_0_t_user = 694.260 self.lambda_r1 = 694.260 self.temperature = 295 self.pressure = 0.00
def __init__(self): self.stopped = True self.ptrn = 0 self.devices = sb.list_devices() self.spec = sb.Spectrometer(self.devices[0]) self.spec.integration_time_micros(100000) self.xs = self.spec.wavelengths() self.ys = self.spec.intensities() self.xs_roi = np.zeros(300) self.ys_roi = np.zeros(300) self.timer = QtCore.QTimer() # pressure calculation parameters # lambda zero (ref) is 694.260 based on Ragan et al JAP 72, 5539 (1992) at 295K self.alpha = 1885 self.beta = 11.0 self.lambda_0_ref = 694.260 self.lambda_0_user = 694.260 self.lambda_0_t_user = 694.260 self.lambda_r1 = 694.260 self.temperature = 295 self.pressure = 0.00
def __init__(self): # global variables that may or may not be used later on self.stopped = True self.ptrn = 0 # get spectrometer going self.devices = sb.list_devices() self.spec = sb.Spectrometer(self.devices[0]) self.spec.integration_time_micros(100000) # initial real and dummy spectra self.xs = self.spec.wavelengths() self.ys = self.spec.intensities() default_zoom = np.abs(self.xs - 694.260).argmin() self.xs_roi = self.xs[default_zoom - 150:default_zoom + 150] self.ys_roi = self.ys[default_zoom - 150:default_zoom + 150] self.timer = QtCore.QTimer() # pressure calculation parameters # lambda zero (ref) is 694.260 based on Ragan et al JAP 72, 5539 (1992) at 295K self.alpha = 1885 self.beta = 11.0 self.lambda_0_ref = 694.260 self.lambda_0_user = 694.260 self.lambda_0_t_user = 694.260 self.lambda_r1 = 694.260 self.temperature = 295 self.pressure = 0.00
def test_read_serial_number(backendlified_serial): devices = list(list_devices()) if len(devices) == 0: pytest.skip("no supported device connected") spec = Spectrometer.from_serial_number(backendlified_serial) serial = spec.serial_number assert len(serial) > 0
def test_read_spectrum(backendlified_serial): devices = list(list_devices()) if len(devices) == 0: pytest.skip("no supported device connected") spec = Spectrometer.from_serial_number(backendlified_serial) arr = spec.spectrum() assert arr.shape == (2, spec.pixels)
def init_device(self): # call list of all connected spectrometers devices = sb.list_devices() # create object for spectrometers(s) self.spec = sb.Spectrometer(devices[0]) return self.FLAG_done
def start(): os.system("killall matchbox-keyboard") global uploadInterval f = open('config.txt', "r") conf = [row[0] for row in csv.reader(f, delimiter='\t')] f.close() sessionBegin = timeToMinutes(conf[4]) sessionEnd = timeToMinutes(conf[5]) print(sessionBegin) print(sessionEnd) uploadInterval = int(conf[6], 10) print("spectrometer flag is") print(spectrometerFlag) durationValue = conf[3] devices = sb.list_devices() frame.grid_forget() if (len(devices) > 0): spec = sb.Spectrometer(devices[0]) spec.integration_time_micros(int(conf[2], 10)) else: spec = 0 uploadText = tk.StringVar() frame3 = Frame(root) frame3.grid(row=0) stopButton = Button(frame3, text=" Stop ", command=stop) stopButton.grid(row=1, column=0) startButton = Button(frame3, text=" Start ", command=startscan) startButton.grid(row=1, column=1) button = Button(frame3, text="QUIT", command=quit) button.grid(row=1, column=2) uploadLabel = Label(frame3, textvariable=uploadText) uploadLabel.grid(row=0, column=4, pady=6) w0 = Label(frame3, text="Reading in process", font='Helvetica 14 bold') w0.grid(row=0, pady=6) root.update() ftpVar = ftp.get() ftpUserVar = ftpUser.get() ftpPassVar = ftpPass.get() waitTime = 10 print("going into the while loop") count = 0 while (1): currentTime = time.localtime().tm_min + time.localtime().tm_hour * 60 print(currentTime) if (currentTime >= sessionBegin and currentTime <= sessionEnd): print(" it is looping though") print(currentTime) uploadText.set('Time from last upload:' + str(currentTime - uploadTime)) print(uploadText.get()) scanning(durationValue, spec, currentTime, ftpVar, ftpUserVar, ftpPassVar) # After 1 second, call scanning time.sleep(waitTime) else: time.sleep(20) root.update()
def test_list_devices_dont_close_opened_devices(): """test list_devices() interaction with already opened devices""" devices = list(list_devices()) if len(devices) == 0: pytest.skip("no supported device connected") num_devices = len(devices) dev = devices[0] dev.open() assert dev.is_open is True devices_2 = list_devices() assert len(devices_2) == num_devices # dev.is_open is still True here... assert dev.is_open is True # but if we delete the new reference created by the second call to list_devices: del devices_2 assert dev.is_open is True
def set_spectrometer(self): spectrometers = sb.list_devices() for spec in spectrometers: if str(spec) == self.comboBox.currentText(): try: self.spectrometer = sb.Spectrometer(spec) self.alert_message("Connected to: " + str(spec)) except: pass
def test_max_intensity(backendlified_serial): devices = list(list_devices()) if len(devices) == 0: pytest.skip("no supported device connected") spec = Spectrometer.from_serial_number(backendlified_serial) value = spec.max_intensity assert isinstance(value, float) assert 0 < value < 1e8
def get_spectrometer_list(self): try: spectrometers = sb.list_devices() spectrometer_list = [] for spec in spectrometers: spectrometer_list.append(str(spec)) except: spectrometer_list = "No devices found" return spectrometer_list
def automatic(): global spec print("automatic mode here we go") print("spectrometer flag is") print(spectrometerFlag) durationValue = duration.get() calibrateValue = calibration.get() fillValue = int(fillWait.get()) devices = sb.list_devices() frame2 = Frame(root, width=450, height=50) frame2.grid(row=0) if spectrometerFlag: spec.integration_time_micros(int(integrationTime.get(), 10)) else: spec = 0 if calibrateValue: #code to turn on nitrogen valve print("turning on valve for nitrogen") w0 = Label(frame2, text="Opening valve for Nitrogen Please wait... ", font='Helvetica 14 bold') w0.grid(row=0, pady=6) root.update() time.sleep(fillValue) w0.grid_forget() print("Reading Values") nitrogenData = getdata(durationValue, spec) print(nitrogenData) #code to turn on CO2 valve print("turning on valve for CO2") w0 = Label(frame2, text="Opening valve for CO2 Please wait... ", font='Helvetica 14 bold') w0.grid(row=0, pady=6) root.update() time.sleep(fillValue) w0.grid_forget() print("Reading Values") secondData = getdata(durationValue, spec) print(secondData) alpha = alphaCalculation(nitrogenData, secondData) #code to turn on air valve print("turning on valve for air") w0 = Label(frame2, text="Opening valve for air Please wait... ", font='Helvetica 14 bold') w0.grid(row=0, pady=6) root.update() time.sleep(fillValue) frame2.grid_forget() print("Reading Values") measurement(durationValue, spec)
def test_integration_time_limits(backendlified_serial): devices = list(list_devices()) if len(devices) == 0: pytest.skip("no supported device connected") spec = Spectrometer.from_serial_number(backendlified_serial) low, high = spec.integration_time_micros_limits assert isinstance(low, int) assert isinstance(high, int) assert 0 < low < high < 2**64
def openSpec(): devices = sb.list_devices() if not len(devices): print("Error: No OceanOptic Device found") sys.exit(1) for device in devices: print(device) spec = sb.Spectrometer(devices[0]) return spec
def __init__(self): try: sb.list_devices() if len(sb.list_devices()) == 0: print("No spectrometer is detected! \n") self.Error = 1 return else: self.detect() except Exception, e: if (e.message == 'This should not have happened. Apparently this device has 0 serial number features. The code expects it to have 1 and only 1. Please file a bug report including a description of your device.' ): #print ('Please unplug the spectrometer and then plug again. Then close the python command line and reopen it. Last') print( 'Unplug the spectrometer and then plug again, then close the python command line and reopen it.' ) self.Error = 1 return
def connect(self): try: import seabreeze.spectrometers as sp self.instrument = sp.Spectrometer(sp.list_devices()[0]) self.name = self.instrument.model print(self.name) self.connected = True except: print('Spectrometer not connected') self.name = 'Virtual device'
def connectSpec(self): try: devices = sb.list_devices() self.spec = sb.Spectrometer(devices[0]) self.wav = self.spec.wavelengths() self.connected = True return True except (SeaBreezeError, IndexError): self.connected = False return False
def OOinit(): # Init & test spectrometer(s) # Find spectrometers & print list devices = sb.list_devices() print(devices) # Test spectrometers in the list, 15 frames each [OO.run(devices, devID=n, frames=15) for n in range(len(devices))] return devices
def connectOO(self): devices = sb.list_devices() self.cam = sb.Spectrometer(devices[0]) self.exp = self.cam.minimum_integration_time_micros / 1000 + 1.0 self.cam.integration_time_micros(self.exp * 1000) self.expmin, self.expmax, self.expinc = self.exp, 65000, 2 self.satlevel = self.cam._dev.interface._MAX_PIXEL_VALUE self.wlAxis = self.cam.wavelengths()[sensor_active_pixels[0]:sensor_active_pixels[1]] self.activeCam = 'OO'
def spectrometerConnect(): devices=sb.list_devices() print(devices) if(len(devices)>0): spectrometerFlag=1 print("Something is connected") messagebox.showinfo("Detected", "Spectrometer detected :"+str(devices[0])) return 1 else: messagebox.showinfo("Error", "No spectrometer detected") return 0
def __init__(self, int_time=1500): devices = sb.list_devices() # Find the spectrometer, there is only one if len(devices) > 1: print(devices) if len(devices) < 1: raise Exception("No spectrometer connected to computer") self.spec = sb.Spectrometer(devices[0]) self.min_int_time = self.spec.minimum_integration_time_micros self.wavelengths = self.spec.wavelengths() self.int_time = int_time self.set_int_time_ms(int_time)
def connectOO(self): devices = sb.list_devices() self.cam = sb.Spectrometer(devices[0]) self.exp = self.cam.minimum_integration_time_micros / 1000 + 1.0 self.cam.integration_time_micros(self.exp * 1000) self.expmin, self.expmax, self.expinc = self.exp, 65000, 2 self.satlevel = self.cam._dev.interface._MAX_PIXEL_VALUE self.wlAxis = self.cam.wavelengths( )[sensor_active_pixels[0]:sensor_active_pixels[1]] self.activeCam = 'OO'
def connect(self): self.device = None try: devices = list_devices() except: devices = list_devices() for device in devices: pyusb_device = device._raw_device.pyusb_device if pyusb_device.idVendor == self.device_id.vid and pyusb_device.idProduct == self.device_id.pid: self.device = device if self.device == None: log.error("Ocean Device: No ocean device found. Returning") self.message_queue.put_nowait(None) return False self.spec = Spectrometer(self.device) self.settings.eeprom.model = self.device.model self.settings.eeprom.serial_number = self.device.serial_number self.settings.eeprom.active_pixels_horizontal = self.device.features[ 'spectrometer'][0]._spectrum_num_pixel self.settings.eeprom.detector = "Ocean" # Ocean API doesn't have access to detector info return True
def __init__(self): self.intensities_max = [] self.intensities_min = [] self.intensities_read = [] warnings.filterwarnings('ignore') devices = sb.list_devices() self.spec = sb.Spectrometer(devices[0]) self.spec.integration_time_micros(12000) self.wavelengths = self.spec.wavelengths() self.percentage_wave = self.wavelengths
def connect(self): # Open connection to the device: devices = sb.list_devices() self.spec = sb.Spectrometer(devices[0]) #Connect settings to hardware: self.settings.intg_time.connect_to_hardware( self.spec.integration_time_micros(self.settings['intg_time'] * 1000)) #Take an initial sample of the data. self.read_from_hardware()
def _init_spectrometer(self): try: devices = sb.list_devices() self._spectrometer = sb.Spectrometer(devices[0]) self._spectrometer.tec_set_temperature_C(-15) self._spectrometer.tec_set_enable(True) self._spectrometer.integration_time_micros(100000) print(self._spectrometer.tec_get_temperature_C()) print("Spectrometer " + str(self._spectrometer.serial_number) + " initialized and working") except: #print("Error opening Spectrometer, using Dummy instead") print("Error accessing Spectrometer")
def Detect (): devices = sb.list_devices() print devices spec = sb.Spectrometer(devices[0]) print 'Serial number:%s' % spec.serial_number print 'Model:%s' % spec.model print 'minimum_integration_time_micros:' spec.minimum_integration_time_micros spec.trigger_mode(0) #Flushing the stuff down and make the spectrometer ready for next steps! spec.integration_time_micros(10000) spec.wavelengths() Intensities = spec.intensities(correct_dark_counts=True, correct_nonlinearity=True) Intensities = spec.intensities(correct_dark_counts=True, correct_nonlinearity=True) return spec
def connect_to_spectrometer(intTime=1000000,darkChannel=6,numberOfScans=15): #connects to first connected spectrometer it finds, takes intTime as integration time in microseconds, darkChannel as #multiplexer channel that is blocked from all light #default int time is 1s, channel6 on the multiplexer is blocked off on MC02 #measures dark spectrum #returns the spectrometer instance, spectrometer wavelengths, and measured dark spectrum time.sleep(1) # sometimes needs a small delay here...don't know why devices = sb.list_devices() #print devices[0] #use this line to print device name time.sleep(1) #need to wait for a second, otherwise gives error in next step spec = sb.Spectrometer(devices[0]) spec.integration_time_micros(intTime) return spec
def performOpen(self, options={}): """Perform the operation of opening the instrument connection""" # init object self.spec = None try: # open connection devices = sb.list_devices() # check if devices available if len(devices) == 0: # no devices found raise Exception('No spectrometer found') elif len(devices) == 1: # one device, use self.spec = sb.Spectrometer(devices[0]) else: # many devices, look for serial self.spec = sb.Spectrometer.from_serial_number(self.comCfg.address) except Exception as e: # re-cast errors as a generic communication error raise InstrumentDriver.CommunicationError(str(e))
def connect_to_spectrometer(intTime=1000000,darkChannel=6): #connects to first connected spectrometer it finds, takes intTime as integration time in nanoseconds, darkChannel as #multiplexer channel that is blocked from all light #default int time is 1s, channel6 on the multiplexer is blocked off on MC02 #measures dark spectrum #returns the spectrometer instance, spectrometer wavelengths, and measured dark spectrum devices = sb.list_devices() #print devices[0] #use this line to print device name time.sleep(1) #need to wait for a second, otherwise gives error in next step spec = sb.Spectrometer(devices[0]) spec.integration_time_micros(intTime) #actually in nanoseconds not microseconds...WTF mpdll.MPM_SetChannel(darkChannel) time.sleep(1) # have to wait at least 0.5s for multiplexer to switch #averages 15 measurements for the dark backround spectrum darkInt = spec.intensities() for each in range(14): darkInt += spec.intensities() darkInt = darkInt/15.0 return spec, spec.wavelengths(), darkInt
def sample_spectrum(path, logging): """Sample the spectrum and store the file locally""" file_name = get_file_name() try: # Get the Spectrometer devices = sb.list_devices() spec = sb.Spectrometer(devices[0]) print "[ VISPECS ] Spectrometer:" + spec.model # Read data wavelengths = spec.wavelengths() intensities = spec.intensities() # Storing in hdf5 spect_file = h5py.File(path + file_name + SPECTRUM_FORMAT, "w") spect_grp = spect_file.create_group("grp_spectrum") # Store the pi/system name as an attribute of this group spect_grp.attrs.__setitem__("attr_system", PI_NAME) # Store the utc datetime as an attribute of this group spect_grp.attrs.__setitem__("attr_datetime", DATETIME) # Dataset for storing the wavelengths wavelength_dataset = spect_grp.create_dataset("dataset_wavelengths", data=wavelengths) # Dataset for storing the intensities intensities_dataset = spect_grp.create_dataset("dataset_intensities", data=intensities) # Close the spectrum file spect_file.close() print "[ VISPECS ] Spectrum file: " + path + file_name + SPECTRUM_FORMAT logging.info("Spectrum file: " + path + file_name + SPECTRUM_FORMAT) except Exception as error: print "[ VISPECS ] Exception when reading spectrum!" print error logging.info("Spectrum Exception!: " + repr(error))
def connect_to_spectrometer(intTime=procIntTime,darkChannel=6,numberOfScans=procNumScans): # connects to first connected spectrometer it finds, takes intTime as integration time in microseconds, darkChannel as # multiplexer channel that is blocked from all light # default int time is 1s, channel6 on the multiplexer is blocked off on MC02 # measures dark spectrum # returns the spectrometer instance, spectrometer wavelengths, and measured dark spectrum time.sleep(1) devices = sb.list_devices() # print devices[0] #use this line to print device name time.sleep(1) #need to wait for a second, otherwise gives error in next step try: spec = sb.Spectrometer(devices[0]) except IndexError: print 'couldn\'t find spectrometer.' print 'try unplugging usb cable from spectrometer and restart measurement' raw_input('press enter to exit') exit() spec.integration_time_micros(intTime) mpdll.MPM_SetChannel(darkChannel) time.sleep(1) # have to wait at least 0.5s for multiplexer to switch print 'taking background reading, should take ', str(2*numberOfScans*intTime/(1000000.)),'seconds' darkInt = spec.intensities(correct_dark_counts=True, correct_nonlinearity=True) for each in range(numberOfScans*2 - 1): darkInt += spec.intensities(correct_dark_counts=True, correct_nonlinearity=True) darkInt = darkInt/float(numberOfScans*2) wl = spec.wavelengths() # write darkInt to file in case its needed if not os.path.isdir(savedir): os.mkdir(savedir) if not os.path.isfile(savedir + savedate + ' -- ' + ' OES raw spectra -- Dark Int.csv'): notWritten = True while notWritten: try: with open(savedir + savedate + ' -- ' + ' OES raw spectra -- Dark Int.csv', 'wb') as csvfile: spamwriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL) spamwriter.writerow(['DateTime']+[eachWL for eachWL in wl]) notWritten = False except IOError: print '\n*****************' print ' raw spectra file (' + savedir + savedate + ' -- ' + ' OES raw spectra -- Dark Int.csv' + ') is open another program, please close it' print '*****************\n' time.sleep(5) notWritten = True while notWritten: try: with open(savedir + savedate + ' -- ' + ' OES raw spectra -- Dark Int.csv', 'ab') as csvfile: spamwriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL) spamwriter.writerow([datetime.strftime(datetime.now(), '%m/%d/%y %H:%M:%S %p')]+[eachInt for eachInt in darkInt]) notWritten = False except IOError: print '\n*****************' print zoneList[each] + ' raw spectra file (' + savedir + savedate + ' -- ' + ' OES raw spectra -- Dark Int.csv' + ') is open another program, please close it' print '*****************\n' time.sleep(5) return spec, spec.wavelengths(), darkInt
import drivers.uc480 as cam cam480 = cam.uc480() cam480.connect() # see whether we can connect sensor_width, _ = cam480.get_sensor_size() cam480.close() uc480avail = True except: sensor_width = 1024 # some default uc480avail = False # import seabreeze module try: import seabreeze seabreeze.use('pyseabreeze') import seabreeze.spectrometers as sb if len(sb.list_devices()) == 0: # count connected OOs raise sensor_active_pixels = (1, -1) OOavail = True except: OOavail = False # --------------------------------------------------------------------------- # main class class pyUVVIS(wx.Frame): # initialize the app window def __init__(self, parent, title): super(pyUVVIS, self).__init__(parent, title=title, style=wx.DEFAULT_FRAME_STYLE | wx.MAXIMIZE)
while not (instr.timeout == 1 and instr.rigol_quirk == False): instr.timeout = 1 instr.rigol_quirk = False idg = '' while not idg: try: idg = instr.ask("*IDN?") except Exception as e: # USBErrors print("{} in get_oscilloscope".format(e)) time.sleep(0.4) print("device info: {}".format(idg)) print("device timeout: {}".format(instr.timeout)) time.sleep(0.5) ## initialize spectrometer devices = sb.list_devices() #t_int=12000 t_int=12000*4 print("Available devices {}".format(devices)) spec = sb.Spectrometer(devices[0]) print("Using {}".format(devices[0])) spec.integration_time_micros(t_int) print("integratiopn time {} seconds.".format(t_int/1e6)) time.sleep(0.5) class DummyFile(object): def write(self, x): pass def nostdout(func): def wrapper(*args, **kwargs): save_stdout = sys.stdout
def __init__(self,device=None,integration_time=20e-3): if device is None: device = sb.Spectrometer(sb.list_devices()[0]) self.device = device self.w = device.wavelengths() self.set_integration_time(integration_time)