diff --git a/src/pymodaq_plugins_hamamatsu/__init__.py b/src/pymodaq_plugins_hamamatsu/__init__.py index fe752d3..cd4e7c1 100644 --- a/src/pymodaq_plugins_hamamatsu/__init__.py +++ b/src/pymodaq_plugins_hamamatsu/__init__.py @@ -1,10 +1,9 @@ -from pymodaq_utils.utils import get_version, PackageNotFoundError from pathlib import Path -from pymodaq.utils.logger import set_logger # to be imported by other modules. - from .utils import Config -config = Config() +from pymodaq_utils.utils import get_version, PackageNotFoundError +from pymodaq_utils.logger import set_logger, get_module_name +config = Config() try: __version__ = get_version(__package__) except PackageNotFoundError: diff --git a/src/pymodaq_plugins_hamamatsu/app/custom_app_template.py b/src/pymodaq_plugins_hamamatsu/app/custom_app_template.py deleted file mode 100644 index fdc49bc..0000000 --- a/src/pymodaq_plugins_hamamatsu/app/custom_app_template.py +++ /dev/null @@ -1,125 +0,0 @@ -from qtpy import QtWidgets - -from pymodaq.utils import gui_utils as gutils -from pymodaq.utils.config import Config -from pymodaq.utils.logger import set_logger, get_module_name - -# todo: replace here *pymodaq_plugins_template* by your plugin package name -from pymodaq_plugins_template.utils import Config as PluginConfig - -logger = set_logger(get_module_name(__file__)) - -main_config = Config() -plugin_config = PluginConfig() - - -# todo: modify the name of this class to reflect its application and change the name in the main -# method at the end of the script -class CustomAppTemplate(gutils.CustomApp): - - # todo: if you wish to create custom Parameter and corresponding widgets. These will be - # automatically added as children of self.settings. Morevover, the self.settings_tree will - # render the widgets in a Qtree. If you wish to see it in your app, add is into a Dock - params = [] - - def __init__(self, parent: gutils.DockArea): - super().__init__(parent) - - self.setup_ui() - - def setup_docks(self): - """Mandatory method to be subclassed to setup the docks layout - - Examples - -------- - >>>self.docks['ADock'] = gutils.Dock('ADock name') - >>>self.dockarea.addDock(self.docks['ADock']) - >>>self.docks['AnotherDock'] = gutils.Dock('AnotherDock name') - >>>self.dockarea.addDock(self.docks['AnotherDock'''], 'bottom', self.docks['ADock']) - - See Also - -------- - pyqtgraph.dockarea.Dock - """ - # todo: create docks and add them here to hold your widgets - # reminder, the attribute self.settings_tree will render the widgets in a Qtree. - # If you wish to see it in your app, add is into a Dock - raise NotImplementedError - - def setup_actions(self): - """Method where to create actions to be subclassed. Mandatory - - Examples - -------- - >>> self.add_action('quit', 'Quit', 'close2', "Quit program") - >>> self.add_action('grab', 'Grab', 'camera', "Grab from camera", checkable=True) - >>> self.add_action('load', 'Load', 'Open', "Load target file (.h5, .png, .jpg) or data from camera" - , checkable=False) - >>> self.add_action('save', 'Save', 'SaveAs', "Save current data", checkable=False) - - See Also - -------- - ActionManager.add_action - """ - raise NotImplementedError(f'You have to define actions here') - - def connect_things(self): - """Connect actions and/or other widgets signal to methods""" - raise NotImplementedError - - def setup_menu(self): - """Non mandatory method to be subclassed in order to create a menubar - - create menu for actions contained into the self._actions, for instance: - - Examples - -------- - >>>file_menu = self.mainwindow.menuBar().addMenu('File') - >>>self.affect_to('load', file_menu) - >>>self.affect_to('save', file_menu) - - >>>file_menu.addSeparator() - >>>self.affect_to('quit', file_menu) - - See Also - -------- - pymodaq.utils.managers.action_manager.ActionManager - """ - # todo create and populate menu using actions defined above in self.setup_actions - pass - - def value_changed(self, param): - """ Actions to perform when one of the param's value in self.settings is changed from the - user interface - - For instance: - if param.name() == 'do_something': - if param.value(): - print('Do something') - self.settings.child('main_settings', 'something_done').setValue(False) - - Parameters - ---------- - param: (Parameter) the parameter whose value just changed - """ - pass - - -def main(): - from pymodaq.utils.gui_utils.utils import mkQApp - app = mkQApp('CustomApp') - - mainwindow = QtWidgets.QMainWindow() - dockarea = gutils.DockArea() - mainwindow.setCentralWidget(dockarea) - - # todo: change the name here to be the same as your app class - prog = CustomAppTemplate(dockarea) - - mainwindow.show() - - app.exec() - - -if __name__ == '__main__': - main() diff --git a/src/pymodaq_plugins_hamamatsu/daq_move_plugins/__init__.py b/src/pymodaq_plugins_hamamatsu/daq_move_plugins/__init__.py index 9e175ad..1470a45 100644 --- a/src/pymodaq_plugins_hamamatsu/daq_move_plugins/__init__.py +++ b/src/pymodaq_plugins_hamamatsu/daq_move_plugins/__init__.py @@ -1,7 +1,7 @@ import importlib from pathlib import Path -from pymodaq.daq_utils import daq_utils as utils -logger = utils.set_logger('move_plugins', add_to_console=False) +from .. import set_logger +logger = set_logger('move_plugins', add_to_console=False) for path in Path(__file__).parent.iterdir(): try: @@ -10,4 +10,3 @@ except Exception as e: logger.warning("{:} plugin couldn't be loaded due to some missing packages or errors: {:}".format(path.stem, str(e))) pass - diff --git a/src/pymodaq_plugins_hamamatsu/daq_viewer_plugins/plugins_1D/__init__.py b/src/pymodaq_plugins_hamamatsu/daq_viewer_plugins/plugins_1D/__init__.py index 19e5b12..73284cf 100644 --- a/src/pymodaq_plugins_hamamatsu/daq_viewer_plugins/plugins_1D/__init__.py +++ b/src/pymodaq_plugins_hamamatsu/daq_viewer_plugins/plugins_1D/__init__.py @@ -9,4 +9,4 @@ importlib.import_module('.' + path.stem, __package__) except Exception as e: logger.warning("{:} plugin couldn't be loaded due to some missing packages or errors: {:}".format(path.stem, str(e))) - pass \ No newline at end of file + pass diff --git a/src/pymodaq_plugins_hamamatsu/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MiniSpectro.py b/src/pymodaq_plugins_hamamatsu/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MiniSpectro.py index 14a6311..9607eab 100644 --- a/src/pymodaq_plugins_hamamatsu/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MiniSpectro.py +++ b/src/pymodaq_plugins_hamamatsu/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MiniSpectro.py @@ -1,13 +1,18 @@ import numpy as np -from pymodaq.utils.daq_utils import ThreadCommand -from pymodaq.utils.data import DataFromPlugins, Axis, DataToExport -from pymodaq.control_modules.viewer_utility_classes import DAQ_Viewer_base, comon_parameters, main -from pymodaq.utils.parameter import Parameter +from pymodaq.control_modules.viewer_utility_classes import ( + DAQ_Viewer_base, + comon_parameters, + main, +) +from pymodaq.utils.data import DataFromPlugins +from pymodaq_data.data import Axis, DataToExport +from pymodaq_gui.parameter import Parameter +from pymodaq_utils.utils import ThreadCommand -from pymodaq_plugins_hamamatsu.hardware.minispectro import MiniSpectro +from pymodaq_plugins_hamamatsu.hardware.minispectro import Minispectro -class DAQ_1DViewer_MiniSpectro(DAQ_Viewer_base): +class DAQ_1DViewer_Minispectro(DAQ_Viewer_base): """ Instrument plugin class for Hamamatsu USB Mini-spectrometers. This object inherits all functionalities to communicate with PyMoDAQ's DAQ_Viewer module through inheritance via @@ -20,12 +25,12 @@ class DAQ_1DViewer_MiniSpectro(DAQ_Viewer_base): Tested with PyMoDAQ 4.4.7 on Windows 11. The "specu1b.dll" driver is required and is obtained through the installation of Hamamatsu Tokuspec software. This plugin - should work with the .dll file in its default location (C:\Program Files\Hamamatsu\TokuSpec) but make sure to change its + should work with the .dll file in its default location (C:/Program Files/Hamamatsu/TokuSpec) but make sure to change its path in the python wrapper "minispectro.py" in the case you place it somewhere else. This .dll file can also be found in the installation files of the Hamamatsu Evaluation Software originally provided with the device CD. """ - supported_platforms = ('win32',) # a Windows .NET driver + # supported_platforms = ('win32',) # a Windows .NET driver params = comon_parameters + [ {'title': 'Device ID', 'name': 'unit_id', 'type': 'str', 'value': '', 'readonly': True}, {'title': 'Sensor name', 'name': 'sensor_name', 'type': 'str', 'value': '', 'readonly': True}, @@ -43,33 +48,9 @@ class DAQ_1DViewer_MiniSpectro(DAQ_Viewer_base): ] def ini_attributes(self): - self.controller: MiniSpectro = None + self.controller: Minispectro = None self.x_axis = None - def commit_settings(self, param: Parameter): - """Apply the consequences of a change of value in the detector settings - - Parameters - ---------- - param: Parameter - A given parameter (within detector_settings) whose value has been changed by the user - """ - if param.name() == "integration_time": - self.controller.set_parameter(integ_time=int(self.settings['integration_time']*1e3)) # Convert from ms to µs - if param.name() == 'trig_mode': - if param.value() == 'Internal': - self.controller.set_parameter(trigger_mode=0x00) - elif param.value() == 'External (edge)': - self.controller.set_parameter(trigger_mode=0x01) - elif param.value() == 'External (gate)': - self.controller.set_parameter(trigger_mode=0x02) - if param.name() == 'trig_edge': - if param.value() == 'Rising edge': - self.controller.set_parameter(trigger_mode=0x00) - elif param.value() == 'Falling edge': - self.controller.set_parameter(trigger_mode=0x01) - - def ini_detector(self, controller=None): """Detector communication initialization @@ -85,10 +66,15 @@ def ini_detector(self, controller=None): initialized: bool False if initialization failed otherwise True """ - self.ini_detector_init(slave_controller=controller) + # self.ini_detector_init(slave_controller=controller) if self.is_master: - self.controller = MiniSpectro() + self.controller = Minispectro() + self.controller.connect() + initialized = self.controller.check_connection() + else: + self.controller = controller + initialized = True self.settings.child('unit_id').setValue(self.controller.unit_id) self.settings.child('sensor_name').setValue(self.controller.sensor_name) @@ -106,7 +92,7 @@ def ini_detector(self, controller=None): self.settings.child('gain').setValue('None') self.settings.child('gain').setReadonly() - data_x_axis = self.controller.get_sensor_data()[1]*1e-9 + data_x_axis = np.array(self.controller.wl)*1e-9 # Axis' axes needs array + conversion to nm self.x_axis = Axis(data=data_x_axis, label='Wavelength', units='m', index=0) # Initialize viewers panel with the future type of data @@ -116,13 +102,13 @@ def ini_detector(self, controller=None): dim='Data1D', labels=['Spectrometer'], axes=[self.x_axis])])) - info = "Whatever info you want to log" + info = "Minispectrometer initialized" initialized = True return info, initialized def close(self): """Terminate the communication protocol""" - if self.controller is not None: + if self.is_master and self.controller is not None: self.controller.close() def grab_data(self, Naverage=1, **kwargs): @@ -137,8 +123,8 @@ def grab_data(self, Naverage=1, **kwargs): others optionals arguments """ # Synchrone version (blocking function) - data_tot = self.controller.get_sensor_data()[2] - self.dte_signal.emit(DataToExport(name='MiniSpectro', + data_tot = self.controller.get_sensor_data() + self.dte_signal.emit(DataToExport(name='minispectro', data=[DataFromPlugins(name='Mini-spectrometer', data=data_tot, dim='Data1D', @@ -147,10 +133,32 @@ def grab_data(self, Naverage=1, **kwargs): def stop(self): """ - Stop the current grab by emitting a status. Works by stopping to call get_sensor_data() function) + Stop the current grab by emitting a status. """ - self.emit_status(ThreadCommand('Update_Status', ['Some info you want to log'])) + self.emit_status(ThreadCommand('Update_Status', ['Useless for mini-spectrometers (no existing stop function)'])) + + def commit_settings(self, param: Parameter): + """Apply the consequences of a change of value in the detector settings + Parameters + ---------- + param: Parameter + A given parameter (within detector_settings) whose value has been changed by the user + """ + if param.name() == "integration_time": + self.controller.set_parameter(integ_time=int(self.settings['integration_time']*1e3)) # Convert from ms to µs + if param.name() == 'trig_mode': + if param.value() == 'Internal': + self.controller.set_parameter(trigger_mode=0x00) + elif param.value() == 'External (edge)': + self.controller.set_parameter(trigger_mode=0x01) + elif param.value() == 'External (gate)': + self.controller.set_parameter(trigger_mode=0x02) + if param.name() == 'trig_edge': + if param.value() == 'Rising edge': + self.controller.set_parameter(trigger_mode=0x00) + elif param.value() == 'Falling edge': + self.controller.set_parameter(trigger_mode=0x01) if __name__ == '__main__': main(__file__) \ No newline at end of file diff --git a/src/pymodaq_plugins_hamamatsu/daq_viewer_plugins/plugins_2D/daq_2Dviewer_Hamamatsu.py b/src/pymodaq_plugins_hamamatsu/daq_viewer_plugins/plugins_2D/daq_2Dviewer_Hamamatsu.py index 160cc24..adf1948 100644 --- a/src/pymodaq_plugins_hamamatsu/daq_viewer_plugins/plugins_2D/daq_2Dviewer_Hamamatsu.py +++ b/src/pymodaq_plugins_hamamatsu/daq_viewer_plugins/plugins_2D/daq_2Dviewer_Hamamatsu.py @@ -1,8 +1,11 @@ import numpy as np -from pymodaq.utils.daq_utils import ThreadCommand -from pymodaq.utils.data import DataFromPlugins, Axis, DataToExport +from pymodaq_utils.utils import ThreadCommand +from pymodaq_data.data import DataToExport, Axis +from pymodaq_gui.parameter import Parameter + from pymodaq.control_modules.viewer_utility_classes import DAQ_Viewer_base, comon_parameters, main -from pymodaq.utils.parameter import Parameter + +from pymodaq.utils.data import DataFromPlugins import pylablib as pll pll.par["devices/dlls/dcamapi"] = "C:/Windows/System32" @@ -10,16 +13,18 @@ from qtpy import QtWidgets, QtCore from time import perf_counter -camera_number = DCAM.get_cameras_number() -if camera_number == 0: - raise Exception('No DCAM camera was found.') - class DAQ_2DViewer_Hamamatsu(DAQ_Viewer_base): """ + Instrument plugin class for DCAM Hamamatsu cameras. """ + + # camera_number = DCAM.get_cameras_number() + # if camera_number == 0: + # raise Exception('No DCAM camera was found.') + params = comon_parameters + [ - {'title': 'Camera index:', 'name': 'camera_index', 'type': 'int', 'value': 0, 'min': 0, 'max': camera_number}, + {'title': 'Camera index:', 'name': 'camera_index', 'type': 'int', 'value': 0}, {'title': 'Camera model:', 'name': 'camera_name', 'type': 'str', 'value': '', 'readonly': True}, {'title': 'Update ROI', 'name': 'update_roi', 'type': 'bool_push', 'value': False}, {'title': 'Clear ROI+Bin', 'name': 'clear_roi', 'type': 'bool_push', 'value': False}, @@ -48,61 +53,6 @@ def ini_attributes(self): # Disable "use ROI" option to avoid confusion with other buttons self.settings.child('ROIselect', 'use_ROI').setOpts(visible=False) - def commit_settings(self, param: Parameter): - """Apply the consequences of a change of value in the detector settings - - Parameters - ---------- - param: Parameter - A given parameter (within detector_settings) whose value has been changed by the user - """ - if param.name() == "exposure_time": - self.controller.set_exposure(param.value() / 1000) - - if param.name() == "fps_on": - self.settings.child('timing_opts', 'fps').setOpts(visible=param.value()) - - if param.name() == "update_roi": - if param.value(): # Switching on ROI - - # We handle ROI and binning separately for clarity - (old_x, _, old_y, _, xbin, ybin) = self.controller.get_roi() # Get current binning - - # Values need to be rescaled by binning factor and shifted by current x0,y0 to be correct. - new_x = (old_x + self.settings.child('ROIselect', 'x0').value()) * xbin - new_y = (old_y + self.settings.child('ROIselect', 'y0').value()) * xbin - new_width = self.settings.child('ROIselect', 'width').value() * ybin - new_height = self.settings.child('ROIselect', 'height').value() * ybin - - new_roi = (new_x, new_width, xbin, new_y, new_height, ybin) - self.update_rois(new_roi) - # recenter rectangle - self.settings.child('ROIselect', 'x0').setValue(0) - self.settings.child('ROIselect', 'y0').setValue(0) - param.setValue(False) - - if param.name() == 'binning': - # We handle ROI and binning separately for clarity - (x0, w, y0, h, *_) = self.controller.get_roi() # Get current ROI - xbin = self.settings.child('binning').value() - ybin = self.settings.child('binning').value() - new_roi = (x0, w, xbin, y0, h, ybin) - self.update_rois(new_roi) - - if param.name() == "clear_roi": - if param.value(): # Switching on ROI - wdet, hdet = self.controller.get_detector_size() - # self.settings.child('ROIselect', 'x0').setValue(0) - # self.settings.child('ROIselect', 'width').setValue(wdet) - self.settings.child('binning').setValue(1) - # - # self.settings.child('ROIselect', 'y0').setValue(0) - # new_height = self.settings.child('ROIselect', 'height').setValue(hdet) - - new_roi = (0, wdet, 1, 0, hdet, 1) - self.update_rois(new_roi) - param.setValue(False) - def ini_detector(self, controller=None): """Detector communication initialization @@ -263,9 +213,9 @@ def update_fps(self): # Update reading self.settings.child('timing_opts', 'fps').setValue(round(self.fps, 1)) - def callback(self): - """optional asynchrone method called when the detector has finished its acquisition of data""" - raise NotImplementedError + # def callback(self): + # """optional asynchrone method called when the detector has finished its acquisition of data""" + # raise NotImplementedError def close(self): """ @@ -283,6 +233,59 @@ def stop(self): self.controller.stop_acquisition() self.controller.clear_acquisition() return '' + + def commit_settings(self, param: Parameter): + """Apply the consequences of a change of value in the detector settings + + Parameters + ---------- + param: Parameter + A given parameter (within detector_settings) whose value has been changed by the user + """ + if param.name() == "exposure_time": + self.controller.set_exposure(param.value() / 1000) + + if param.name() == "fps_on": + self.settings.child('timing_opts', 'fps').setOpts(visible=param.value()) + + if param.name() == "update_roi" and param.value(): # Switching on ROI + # We handle ROI and binning separately for clarity + (old_x, _, old_y, _, xbin, ybin) = self.controller.get_roi() # Get current binning + + # Values need to be rescaled by binning factor and shifted by current x0,y0 to be correct. + new_x = (old_x + self.settings.child('ROIselect', 'x0').value()) * xbin + new_y = (old_y + self.settings.child('ROIselect', 'y0').value()) * xbin + new_width = self.settings.child('ROIselect', 'width').value() * ybin + new_height = self.settings.child('ROIselect', 'height').value() * ybin + + new_roi = (new_x, new_width, xbin, new_y, new_height, ybin) + self.update_rois(new_roi) + # recenter rectangle + self.settings.child('ROIselect', 'x0').setValue(0) + self.settings.child('ROIselect', 'y0').setValue(0) + param.setValue(False) + + if param.name() == 'binning': + # We handle ROI and binning separately for clarity + (x0, w, y0, h, *_) = self.controller.get_roi() # Get current ROI + xbin = self.settings.child('binning').value() + ybin = self.settings.child('binning').value() + new_roi = (x0, w, xbin, y0, h, ybin) + self.update_rois(new_roi) + + if param.name() == "clear_roi": + if param.value(): # Switching on ROI + wdet, hdet = self.controller.get_detector_size() + # self.settings.child('ROIselect', 'x0').setValue(0) + # self.settings.child('ROIselect', 'width').setValue(wdet) + self.settings.child('binning').setValue(1) + # + # self.settings.child('ROIselect', 'y0').setValue(0) + # new_height = self.settings.child('ROIselect', 'height').setValue(hdet) + + new_roi = (0, wdet, 1, 0, hdet, 1) + self.update_rois(new_roi) + param.setValue(False) class DCAMCallback(QtCore.QObject): diff --git a/src/pymodaq_plugins_hamamatsu/hardware/minispectro.py b/src/pymodaq_plugins_hamamatsu/hardware/minispectro.py index 6aa1984..c8fac0a 100644 --- a/src/pymodaq_plugins_hamamatsu/hardware/minispectro.py +++ b/src/pymodaq_plugins_hamamatsu/hardware/minispectro.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Created on Mon Nov 25 14:20:19 2024 @@ -22,11 +21,11 @@ import numpy as np import System -DLL = specu1b() +driver = specu1b() unit_param = UNIT_PARAMETER() unit_info = UNIT_INFORMATION() -class MiniSpectro: +class Minispectro: """ Hamamatsu Minispectrometers class @@ -51,33 +50,54 @@ class MiniSpectro: """ def __init__(self): - for dev in usb.core.find(find_all=True): - if hex(dev.idProduct).find("0x290") == 0: # We make the assumption only Mini-spectrometers - print("Hamamatsu Mini-spectrometer found") # devices have a pid starting with 0x290 - pid = dev.idProduct + self._handle = None + self._is_connected = False + + def connect(self): + if self._is_connected: + raise RuntimeError("Minispectrometer is already connected") + try: + for dev in usb.core.find(find_all=True): + if hex(dev.idProduct).find("0x290") == 0: # We make the assumption only Mini-spectrometers + print("Hamamatsu Mini-spectrometer found") # devices have a pid starting with 0x290 + pid = dev.idProduct - self._handle = DLL.USB_OpenDevice(pid) # Get index of spectrometer from pid + self._handle = driver.USB_OpenDevice(pid) # Get index of spectrometer from pid - if DLL.USB_CheckDevice(self._handle) == 11: - print('Check connection success') - else: - raise ValueError('Check connection failed, please close or reconnect device') + self._pipe = driver.USB_OpenPipe(self._handle) - self._pipe = DLL.USB_OpenPipe(self._handle) + self._c_array = System.Array[System.Double]([0.0 for _ in range(6)]) # 6 calibration values + # self._origin_c_array = System.Array[System.Double]([206.6901787, # Values from TokusPec at 1st boot + # 0.3771377233, + # 3.669128424e-5, + # -1.287399061e-8, + # 5.788371505e-12, + # -1.2738255e-15]) + + self.read_unit_information() + self.get_parameter() + self.read_calibration_value() - self._c_array = System.Array[System.Double]([0.0 for _ in range(6)]) # 6 calibration values - self._origin_c_array = System.Array[System.Double]([206.6901787, # Values from TokusPec at 1st boot - 0.3771377233, - 3.669128424e-5, - -1.287399061e-8, - 5.788371505e-12, - -1.2738255e-15]) + self.buffer_array = System.Array[System.UInt16]([0 for _ in range(self.sensor_size)]) + + except UnboundLocalError as e: # Will get triggered when minispectro is not connected (pid will be None) + self._is_connected = False + print(f"Minispectro does not seem to be connected. Error: {e}") - self.read_unit_information() - self.get_parameter() - self.read_calibration_value() + self._is_connected = self.check_connection() + + def check_connection(self): + if self._handle is None: + self._is_connected = False + return False + if driver.USB_CheckDevice(self._handle) == 11: + print('Check connection success') + self._is_connected = True + else: + self._is_connected = False + raise ValueError('Check connection failed, please close or reconnect Minispectro') - self.buffer_array = System.Array[System.UInt16]([0 for _ in range(self.sensor_size)]) + return self._is_connected def get_parameter(self): """ @@ -103,7 +123,7 @@ def get_parameter(self): reserved_param: Reserved byte """ - DLL.USB_GetParameter(self._handle, unit_param) + driver.USB_GetParameter(self._handle, unit_param) self.integration_time = unit_param.unIntegrationTime self.gain = hex(unit_param.byGain) self.trigger_edge = hex(unit_param.byTriggerEdge) @@ -134,20 +154,20 @@ def set_parameter(self, integ_time=None, gain=None, trigger_edge=None, trigger_m 0x02 (External trigger mode 2 (gate trigger mode)) """ if integ_time is not None: - DLL.USB_GetParameter(self._handle, unit_param)[1].unIntegrationTime = integ_time + driver.USB_GetParameter(self._handle, unit_param)[1].unIntegrationTime = integ_time elif gain is not None: - DLL.USB_GetParameter(self._handle, unit_param)[1].byGain = gain + driver.USB_GetParameter(self._handle, unit_param)[1].byGain = gain elif trigger_edge is not None: - DLL.USB_GetParameter(self._handle, unit_param)[1].byTriggerEdge = trigger_edge + driver.USB_GetParameter(self._handle, unit_param)[1].byTriggerEdge = trigger_edge elif trigger_mode is not None: - DLL.USB_GetParameter(self._handle, unit_param)[1].byTriggerMode = trigger_mode - DLL.USB_SetParameter(self._handle, unit_param) + driver.USB_GetParameter(self._handle, unit_param)[1].byTriggerMode = trigger_mode + driver.USB_SetParameter(self._handle, unit_param) def set_default(self): """ Set all parameters to default. """ - DLL.USB_SetEepromDefaultParameter(self._handle, 0) + driver.USB_SetEepromDefaultParameter(self._handle, 0) def read_unit_information(self): """ @@ -170,7 +190,7 @@ def read_unit_information(self): Upper wavelength the spectrometer is set to detect. Makes it possible to bound to the upper/last pixel on device sensor. """ - DLL.USB_ReadUnitInformation(self._handle, unit_info)[0] + driver.USB_ReadUnitInformation(self._handle, unit_info)[0] self.unit_id = bytearray(unit_info.arybyUnitID).decode('ascii') self.sensor_name = bytearray(unit_info.arybySensorName).decode('ascii') self.serial_number = bytearray(unit_info.arybySerialNumber).decode('ascii') @@ -197,7 +217,7 @@ def write_unit_information(self, flag=None): flag: hex The flag value needs to be 0xAA to allow writing to device. """ - DLL.USB_WriteUnitInformation(self._handle, unit_info, flag) + driver.USB_WriteUnitInformation(self._handle, unit_info, flag) def read_calibration_value(self): """ @@ -207,10 +227,11 @@ def read_calibration_value(self): ------- calibration_list: list(float) List of 6 float values corresponding to A, B1, B2, B3, B4 and B5 calibration coefficients. - λ(nm) = A + B1*pix + B2*pix² + B3*pix³ + B4*pix⁴ + B5*pix⁵ with pix any pixel on sensor. + λ(nm) = a0 + a1*pix + a2*pix² + a3*pix³ + a4*pix⁴ + a5*pix⁵ with pix any pixel on sensor. """ - DLL.USB_ReadCalibrationValue(self._handle, self._c_array) - self.calibration_list = list(self._c_array) + driver.USB_ReadCalibrationValue(self._handle, self._c_array) # Set calibration values into self._c_array + a0, a1, a2, a3, a4, a5 = list(self._c_array) + self.wl = [a0 + a1*x + a2*x**2 + a3*x**3 + a4*x**4 + a5*x**5 for x in range(self.sensor_size)] def write_calibration_value(self, flag=None): """ @@ -221,7 +242,7 @@ def write_calibration_value(self, flag=None): flag: hex The flag value needs to be 0xAA to allow writing to device. """ - DLL.USB_WriteCalibrationValue(self._handle, self._origin_c_array, flag) + driver.USB_WriteCalibrationValue(self._handle, self._origin_c_array, flag) def get_sensor_data(self): """ @@ -236,19 +257,34 @@ def get_sensor_data(self): intensity: numpy.array() 1D measured intensity array with values between 0 and 2^16-1 (65535) """ - pixel_array = np.linspace(0, self.sensor_size-1, self.sensor_size) - wl_array = np.linspace(self.lower_wl, self.upper_wl, self.sensor_size) - intensity = np.array(DLL.USB_GetSensorData(self._handle, self._pipe, self.sensor_size, self.buffer_array)[1]) + if not self._is_connected: + raise RuntimeError("Not connected: call connect() first.") + + count = np.array(driver.USB_GetSensorData(self._handle, self._pipe, self.sensor_size, self.buffer_array)[1]) - return pixel_array, wl_array, intensity + return count def close(self): """ Close device. """ - DLL.USB_ClosePipe(self._handle) - DLL.USB_CloseDevice(self._handle) + if not self._is_connected: + raise RuntimeError("Not connected: call connect() first.") + driver.USB_ClosePipe(self._handle) + driver.USB_CloseDevice(self._handle) + self._is_connected = False if __name__ == "__main__": - spectro = MiniSpectro() \ No newline at end of file + import matplotlib.pyplot as plt + spectro = Minispectro() + spectro.connect() + + count = spectro.get_sensor_data() + + wl = spectro.wl + + plt.plot(wl, count) + plt.show() + + print("Done") \ No newline at end of file