diff --git a/README.rst b/README.rst index 0ac3522..ff6d124 100644 --- a/README.rst +++ b/README.rst @@ -1,46 +1,26 @@ -pymodaq_plugins_template -######################## +pymodaq_plugins_owis +#################### -.. the following must be adapted to your developed package, links to pypi, github description... - -.. image:: https://img.shields.io/pypi/v/pymodaq_plugins_template.svg - :target: https://pypi.org/project/pymodaq_plugins_template/ +.. image:: https://img.shields.io/pypi/v/pymodaq_plugins_owis.svg + :target: https://pypi.org/project/pymodaq_plugins_owis/ :alt: Latest Version .. image:: https://readthedocs.org/projects/pymodaq/badge/?version=latest :target: https://pymodaq.readthedocs.io/en/stable/?badge=latest :alt: Documentation Status -.. image:: https://github.com/PyMoDAQ/pymodaq_plugins_template/workflows/Upload%20Python%20Package/badge.svg - :target: https://github.com/PyMoDAQ/pymodaq_plugins_template - :alt: Publication Status - -.. image:: https://github.com/PyMoDAQ/pymodaq_plugins_template/actions/workflows/Test.yml/badge.svg - :target: https://github.com/PyMoDAQ/pymodaq_plugins_template/actions/workflows/Test.yml +.. image:: https://github.com/jerlfan/pymodaq_plugins_owis/actions/workflows/Test.yml/badge.svg + :target: https://github.com/jerlfan/pymodaq_plugins_owis/actions/workflows/Test.yml -Use this template to create a repository on your account and start the development of your own PyMoDAQ plugin! +PyMoDAQ plugin for OWIS positioning units driven by PS 10 control units, chained on their CANopen bus. -This branch targets **PyMoDAQ 5.3.x** (Python 3.10 to 3.13). Use the branch matching your PyMoDAQ version. +This branch targets **PyMoDAQ 5.3.x** (Python 3.10 to 3.13). Authors ======= -* First Author (myemail@xxx.org) -* Other author (myotheremail@xxx.org) - -.. if needed use this field - - Contributors - ============ - - * First Contributor - * Other Contributors - -.. if needed use this field - - Depending on the plugin type, delete/complete the fields below - +* Jérémie Margueritat (jeremie.margueritat@univ-lyon1.fr) Instruments =========== @@ -50,50 +30,50 @@ Below is the list of instruments included in this plugin Actuators +++++++++ -* **yyy**: control of yyy actuators -* **xxx**: control of xxx actuators - -Viewer0D -++++++++ +* **OWIS_PS10**: OWIS stages driven by PS 10 control units, one axis per unit, the units being chained on their + CANopen bus (tested with HVM100N-30-HiSM, LTM60-25-HSM and DMT65-DM6-HSM stages) -* **yyy**: control of yyy 0D detector -* **xxx**: control of xxx 0D detector -Viewer1D -++++++++ - -* **yyy**: control of yyy 1D detector -* **xxx**: control of xxx 1D detector - - -Viewer2D -++++++++ - -* **yyy**: control of yyy 2D detector -* **xxx**: control of xxx 2D detector +Installation instructions +========================= +* Tested with PyMoDAQ 5.3.10, Python 3.12, Windows 11. +* Install the USB driver of the PS 10, supplied by OWIS with OWISoft. +* Configure each stage once with OWISoft (currents, limit and reference switches, reference velocities): the plugin + uses the parameters stored in the units. Close OWISoft before using the plugin, both use the same serial port. -PID Models -========== +Configuration +============= -Extensions -========== +The serial port and the axes are read from the configuration of the plugin. Describe your setup in your local +configuration file (``config_owis.toml`` in the ``config`` folder of your PyMoDAQ user directory), with +PyMoDAQ closed, since PyMoDAQ rewrites this file when it closes. Each ``[[ps10.axes]]`` block describes one unit, +with the values shown by OWISoft in *Control > Define positioning unit*:: + [ps10] + port = 'COM8' # MOCK to simulate the units -Installation instructions -========================= + [[ps10.axes]] + name = 'X' + stage = 'LTM60-25-HSM' + slave_id = 'master' # else the slave ID of the unit on the CANopen bus + units = 'mm' # 'degree' for a rotation stage + pitch = 1.0 + gear_ratio = 1.0 + fullsteps_per_revolution = 200 + microsteps = 50 + home_position = 12.5 # position reached after the reference run -* PyMoDAQ’s version. -* Operating system’s version. -* What manufacturer’s drivers should be installed to make this plugin run? +The axes of the local file replace those of the template. *Home* runs the reference run of the PS 10 (mode 4: +approach the reference switch, release it, set the position to 0), then moves the axis to its ``home_position``. Development =========== * Install your plugin in editable mode: ``pip install -e .`` -* Check it, without any hardware: ``check_plugin`` (and ``pytest``) +* Check it, without any hardware: ``check_plugin`` and ``pytest tests`` * If you use an AI coding assistant, point it to ``AGENTS.md``: it describes the patterns to follow for instrument plugins, Dashboard extensions (``CustomExt``, whenever instruments are involved) and standalone apps - (``CustomApp``, only if no instruments are needed). + (``CustomApp``, only if no instruments are needed). \ No newline at end of file diff --git a/src/pymodaq_plugins_owis/daq_move_plugins/daq_move_OWIS_PS10.py b/src/pymodaq_plugins_owis/daq_move_plugins/daq_move_OWIS_PS10.py new file mode 100644 index 0000000..e96bfdb --- /dev/null +++ b/src/pymodaq_plugins_owis/daq_move_plugins/daq_move_OWIS_PS10.py @@ -0,0 +1,135 @@ +from pymodaq.control_modules.move_utility_classes import (DAQ_Move_base, comon_parameters_fun, + main, DataActuatorType, DataActuator) +from pymodaq_utils.config import GlobalConfig +from pymodaq_utils.utils import ThreadCommand +from pymodaq_gui.parameter import Parameter +from qtpy import QtCore + + +from pymodaq_plugins_owis.hardware.ps10 import MockPS10Bus, PS10Axis, PS10Bus, PS10Error, slave_id_from_config + +config = GlobalConfig() +AXES = config('owis', 'ps10', 'axes') + + +class DAQ_Move_OWIS_PS10(DAQ_Move_base): + """Actuator plugin for OWIS positioning units driven by PS 10 control units. + + Each PS 10 drives one axis; several units are chained on their CANopen bus, the first one (master) being + connected by USB. One module per axis: the master module opens the bus, the others (same Controller ID, slave) + share it. The axes, their PS 10 slave ID and their mechanical data (as shown by OWISoft in + Control > Define positioning unit) are described in the [[ps10.axes]] blocks of the configuration file. + + Tested with four PS 10-32 units (firmware PS10-V3.0-181010) driving HVM100N-30-HiSM, LTM60-25-HSM and + DMT65-DM6-HSM stages, on Windows 11, Python 3.12, PyMoDAQ 5.3.10. Moves, stop and the reference run (mode 4) + were tested on the hardware; the MOCK port simulates the bus for development and tests. + + Installation: the USB driver of the PS 10 (supplied by OWIS with OWISoft) must be installed. The parameters of + the stages (currents, limit and reference switches, reference velocities) are those stored in the units: + configure each axis once with OWISoft. Close OWISoft before using the plugin, both use the same serial port. + """ + + is_multiaxes = True + _axis_names = [axis['name'] for axis in AXES] + _controller_units = [axis['units'] for axis in AXES] + _epsilons = 0.001 # mm or deg, about ten microsteps of the stages of the default configuration + + data_actuator_type = DataActuatorType.DataActuator + + params = [ + {'title': 'Port:', 'name': 'port', 'type': 'str', 'value': config('owis', 'ps10', 'port')}, + ] + comon_parameters_fun(axis_names=_axis_names) + + def ini_attributes(self): + self.controller: PS10Bus | MockPS10Bus | None = None + self.axis: PS10Axis | None = None + self._home_timer = QtCore.QTimer() + self._home_timer.setInterval(100) + self._home_timer.timeout.connect(self._check_home) + self._returning_home = False + + def ini_stage(self, controller=None): + """Open the bus (master module) or reuse the one of the master, then switch the chosen axis on.""" + if self.is_master: + port = self.settings['port'] + if port == 'MOCK': + self.controller = MockPS10Bus(slave_ids=[slave_id_from_config(axis['slave_id']) for axis in AXES]) + else: + self.controller = PS10Bus(port) + else: + self.controller = controller + self._set_axis() + state = self.axis.state() + return f"{self.axis_name}: {AXES[self.axis_index_key]['stage']}, {state.name}", True + + def _set_axis(self): + """Create the PS10Axis of the axis chosen in the settings and switch it on.""" + self.axis = PS10Axis.from_config(self.controller, AXES[self.axis_index_key]) + self.axis.init() + + def close(self): + """Close the bus, only from the master module that opened it.""" + if self.is_master and self.controller is not None: + self.controller.close() + + def get_actuator_value(self) -> DataActuator: + """Position of the axis, read from the counter of its PS 10.""" + position = DataActuator(data=self.axis.get_position(), units=self.axis_unit) + return self.get_position_with_scaling(position) + + def move_abs(self, value: DataActuator): + """Start a move to the absolute target value; PyMoDAQ then polls the position.""" + value = self.check_bound(value) + self.target_value = value + value = self.set_position_with_scaling(value) + self.axis.move_abs(value.value(self.axis_unit)) + + def move_rel(self, value: DataActuator): + """Start a move by value, as an absolute move to the current position plus value.""" + value = self.check_bound(self.current_value + value) - self.current_value + self.target_value = value + self.current_value + target = self.set_position_with_scaling(self.target_value) + self.axis.move_abs(target.value(self.axis_unit)) + + def move_home(self): + """Reference run of the axis (REF1=4), then move to the home_position of the configuration. + + PyMoDAQ does not poll the position after move_home: _check_home calls move_done at the end. + """ + self._returning_home = False + self.axis.reference() + self._home_timer.start() + + def _check_home(self): + """Called every 100 ms during move_home: chain the reference run and the move to home_position.""" + if self.axis.is_moving(): + return + if not self._returning_home: + if not self.axis.is_referenced(): + self._home_timer.stop() + self.emit_status(ThreadCommand('Update_Status', + [f'reference run of {self.axis_name} failed: {self.axis.state().name}'])) + self.move_done() + return + home_position = AXES[self.axis_index_key].get('home_position', 0.) + if home_position != 0.: + self._returning_home = True + self.axis.move_abs(home_position) + return + self._home_timer.stop() + self.move_done() + + def stop_motion(self): + """Stop the axis and tell PyMoDAQ that the move is over.""" + self._home_timer.stop() + self.axis.stop() + self.move_done() + + def commit_settings(self, param: Parameter): + """Apply a change of the settings.""" + if param.name() == 'axis': + self._set_axis() + + +if __name__ == '__main__': + main(__file__) diff --git a/src/pymodaq_plugins_owis/daq_move_plugins/daq_move_Template.py b/src/pymodaq_plugins_owis/daq_move_plugins/daq_move_Template.py deleted file mode 100644 index 34777b5..0000000 --- a/src/pymodaq_plugins_owis/daq_move_plugins/daq_move_Template.py +++ /dev/null @@ -1,231 +0,0 @@ - -from typing import Union, List, Dict -from pymodaq.control_modules.move_utility_classes import (DAQ_Move_base, comon_parameters_fun, - main, DataActuatorType, DataActuator) -from pymodaq.control_modules.daq_move_ui.utils import UiType - -from pymodaq_utils.utils import ThreadCommand # object used to send info back to the main thread -from pymodaq_gui.parameter import Parameter - -# TODO: -# Replace the following fake import with the import of the real Python wrapper of your instrument. Here we suppose that -# the wrapper is in the hardware directory, but it could come from an external librairy like pylablib or pymeasure. -from pymodaq_plugins_template.hardware.python_wrapper_file_of_your_instrument import PythonWrapperObjectOfYourInstrument - -# TODO: -# (1) change the name of the following class to DAQ_Move_TheNameOfYourChoice -# (2) change the name of this file to daq_move_TheNameOfYourChoice ("TheNameOfYourChoice" should be the SAME -# for the class name and the file name.) -# (3) this file should then be put into the right folder, namely IN THE FOLDER OF THE PLUGIN YOU ARE DEVELOPING: -# pymodaq_plugins_my_plugin/daq_move_plugins - - -class DAQ_Move_Template(DAQ_Move_base): - """ Instrument plugin class for an actuator. - - This object inherits all functionalities to communicate with PyMoDAQ’s DAQ_Move module through inheritance via - DAQ_Move_base. It makes a bridge between the DAQ_Move module and the Python wrapper of a particular instrument. - - TODO Complete the docstring of your plugin with: - * The set of controllers and actuators that should be compatible with this instrument plugin. - * With which instrument and controller it has been tested. - * The version of PyMoDAQ during the test. - * The version of the operating system. - * Installation instructions: what manufacturer’s drivers should be installed to make it run? - - Attributes: - ----------- - controller: object - The particular object that allow the communication with the hardware, in general a python wrapper around the - hardware library. - - # TODO add your particular attributes here if any - - """ - is_multiaxes = False # TODO for your plugin set to True if this plugin is controlled for a multiaxis controller - _axis_names: Union[List[str], Dict[str, int]] = ['Axis1', 'Axis2'] # TODO for your plugin: complete the list - _controller_units: Union[str, List[str]] = 'mm' # TODO for your plugin: put the correct unit here, it could be - # TODO a single str (the same one is applied to all axes) or a list of str (as much as the number of axes) - _epsilons: Union[float, List[float]] = 0.1 # TODO replace this by a value that is correct depending on your controller - # TODO it could be a single float of a list of float (as much as the number of axes) - # _epsilons is the initial default value for the epsilon parameter allowing pymodaq to know if the controller reached - # the target value. It is the developer responsibility to put here a meaningful value - - - data_actuator_type = DataActuatorType.DataActuator # keep this line: move_abs / move_rel receive a DataActuator (with - # units) and get_actuator_value returns one. The default of the PyMoDAQ base class is DataActuatorType.float, only - # kept for old plugins (a plain float in the axis unit is exchanged instead): do not remove this line, and do not - # use DataActuatorType.float in a new plugin. - - #todo: set the correct values for these two variables (pymodaq>5.3.0 only, if developing using lower version, just - # remove the two lines) - ui_type = UiType.NONE # should precise (force if possible) what should be the ui type to be used with this - # actuator. If NONE, PyMoDAQ will use the default ui type (see preferences). - has_encoder = True # tell PyMoDAQ if this actuator is able to set an absolute position and read the controller - # value. If False, you should consider having ui_type = UiType.RELATIVE - - - params = [ # TODO for your custom plugin: elements to be added here as dicts in order to control your custom stage - ] + comon_parameters_fun(axis_names=_axis_names) - - def ini_attributes(self): - # TODO declare the type of the wrapper (and assign it to self.controller) you're going to use for easy - # autocompletion - self.controller: PythonWrapperObjectOfYourInstrument = None - - #TODO declare here attributes you want/need to init with a default value - pass - - def ini_stage(self, controller=None): - """Actuator communication initialization - - Parameters - ---------- - controller: (object) - custom object of a PyMoDAQ plugin (Slave case). None if only one actuator by controller (Master case) - - Returns - ------- - info: str - initialized: bool - False if initialization failed otherwise True - """ - raise NotImplementedError # TODO when writing your own plugin remove this line and modify the ones below - if self.is_master: # is needed when controller is master - self.controller = PythonWrapperObjectOfYourInstrument() # TODO add the arguments for the instantiation - initialized = self.controller.a_method_or_atttribute_to_check_if_init() # todo - # todo: enter here whatever is needed for your controller initialization and eventual - # opening of the communication channel - else: - self.controller = controller - initialized = True - - info = "Whatever info you want to log" - return info, initialized - - def close(self): - """Terminate the communication protocol""" - ## TODO for your custom plugin - raise NotImplementedError # when writing your own plugin remove this line - # only the master owns the controller (a slave must not close the shared one) and ini_stage/ini_detector may - # have failed before creating it, so close can be called while self.controller is still None - if self.is_master and self.controller is not None: - # self.controller.your_method_to_terminate_the_communication() # when writing your own plugin replace this line - ... - - def get_actuator_value(self) -> DataActuator: - """Get the current value from the hardware with scaling conversion. - - Returns - ------- - float: The position obtained after scaling conversion. - """ - ## TODO for your custom plugin - raise NotImplementedError # when writing your own plugin remove this line - pos = DataActuator(data=self.controller.your_method_to_get_the_actuator_value(), # when writing your own plugin replace this line - units=self.axis_unit) - pos = self.get_position_with_scaling(pos) - return pos - - def user_condition_to_reach_target(self) -> bool: - """ Implement a condition for exiting the polling mechanism and specifying that the - target value has been reached - - Returns - ------- - bool: if True, PyMoDAQ considers the target value has been reached - """ - # TODO either delete this method if the usual polling is fine with you, but if need you can - # add here some other condition to be fullfilled either a completely new one or - # using or/and operations between the epsilon_bool and some other custom booleans - # for a usage example see DAQ_Move_brushlessMotor from the Thorlabs plugin - return True - - def move_abs(self, value: DataActuator): - """ Move the actuator to the absolute target defined by value - - Parameters - ---------- - value: DataActuator - Absolute target, with units. (With the backcompatibility DataActuatorType.float it would be a plain float, - already expressed in the axis unit, but new plugins should not use it.) - """ - - value = self.check_bound(value) #if user checked bounds, the defined bounds are applied here - self.target_value = value - value = self.set_position_with_scaling(value) # apply scaling if the user specified one - ## TODO for your custom plugin - # IMPORTANT: the controller only understands its own units. Always send value.value(self.axis_unit), it returns - # the magnitude expressed in the unit of this axis (the one of _controller_units, 'mm' here). PyMoDAQ already - # converts the target to the axis unit before calling move_abs, but value.value() alone is just the magnitude - # in whatever unit `value` carries (1 cm gives 1.0, not 10.0): value.value(self.axis_unit) guards against a - # mistake, and keeps the plugin correct when move_abs is called from elsewhere with another unit. - # (axis_unit is the unit of the current axis, axis_units the list/dict of the units of all the axes.) - raise NotImplementedError # when writing your own plugin remove this line - self.controller.your_method_to_set_an_absolute_value(value.value(self.axis_unit)) # when writing your own plugin replace this line - self.emit_status(ThreadCommand('Update_Status', ['Some info you want to log'])) - - def move_rel(self, value: DataActuator): - """ Move the actuator to the relative target actuator value defined by value - - Parameters - ---------- - value: DataActuator - Relative displacement, with units (convert it with value.value(self.axis_unit) before sending it to the - controller, see move_abs). - """ - value = self.check_bound(self.current_value + value) - self.current_value - self.target_value = value + self.current_value - value = self.set_position_relative_with_scaling(value) - - ## TODO for your custom plugin - # IMPORTANT: send value.value(self.axis_unit), not value.value(): the controller only understands its own units - raise NotImplementedError # when writing your own plugin remove this line - self.controller.your_method_to_set_a_relative_value(value.value(self.axis_unit)) # when writing your own plugin replace this line - self.emit_status(ThreadCommand('Update_Status', ['Some info you want to log'])) - - def move_home(self): - """Call the reference method of the controller - - Contrary to move_abs and move_rel, PyMoDAQ does not poll the position to know when the homing is finished. - Whether this method blocks until the actuator is at home or only starts the homing (asynchronous), the plugin - has to call self.move_done() when the homing process ends, otherwise PyMoDAQ keeps waiting for it. - """ - - ## TODO for your custom plugin - raise NotImplementedError # when writing your own plugin remove this line - self.controller.your_method_to_get_to_a_known_reference() # when writing your own plugin replace this line - self.emit_status(ThreadCommand('Update_Status', ['Some info you want to log'])) - self.move_done() # blocking homing: call it here. Asynchronous homing: call it once the controller reports the end - - def stop_motion(self): - """Stop the actuator and emits move_done signal""" - - ## TODO for your custom plugin - raise NotImplementedError # when writing your own plugin remove this line - self.controller.your_method_to_stop_positioning() # when writing your own plugin replace this line - self.emit_status(ThreadCommand('Update_Status', ['Some info you want to log'])) - - 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 - """ - ## TODO for your custom plugin - if param.name() == 'axis': - self.axis_unit = self.controller.your_method_to_get_correct_axis_unit() - # do this only if you can and if the units are not known beforehand, for instance - # if the motors connected to the controller are of different type (mm, µm, nm, , etc...) - # see BrushlessDCMotor from the thorlabs plugin for an exemple - - elif param.name() == "a_parameter_you've_added_in_self.params": - self.controller.your_method_to_apply_this_param_change() - else: - pass - - -if __name__ == '__main__': - main(__file__) diff --git a/src/pymodaq_plugins_owis/hardware/ps10.py b/src/pymodaq_plugins_owis/hardware/ps10.py new file mode 100644 index 0000000..152994e --- /dev/null +++ b/src/pymodaq_plugins_owis/hardware/ps10.py @@ -0,0 +1,257 @@ +"""Wrapper for OWIS PS 10 control units linked by a CANopen bus. + +The master unit is connected by USB (virtual serial port), the slaves are reached through it by prefixing +each command with their two-digit slave ID. +""" +import time +from enum import Enum + +import serial + +BAUDRATE = 9600 +TERMINATOR = b'\r' +COMMAND_DELAY = 0.05 # s, the manual asks for 20 to 40 ms between two commands +MASTER = 'master' # slave_id of the unit connected by USB in the configuration + +class PS10Error(Exception): + """Raised when a PS 10 unit does not answer a query.""" + + +class PS10Bus: + """Serial link to the master PS 10 and, through it, to its slaves. + + A unit is addressed by its slave ID: None for the master, 1, 2, 3... for the slaves. + """ + + def __init__(self, port: str, baudrate: int = BAUDRATE, timeout: float = 0.5): + self._serial = serial.Serial(port, baudrate, timeout=timeout) + + @staticmethod + def _prefix(slave_id) -> str: + return '' if slave_id is None else f'{slave_id:02d}' + + def write(self, slave_id, command: str): + """Send a command that has no reply (INIT1, PGO1...).""" + self._serial.reset_input_buffer() + self._serial.write((self._prefix(slave_id) + command).encode('ascii') + TERMINATOR) + time.sleep(COMMAND_DELAY) + + def query(self, slave_id, command: str) -> str: + """Send a query (?CNT1, ?ASTAT...) and return its reply without the terminator.""" + self.write(slave_id, command) + reply = self._serial.read_until(TERMINATOR) + if not reply.endswith(TERMINATOR): + unit = 'master' if slave_id is None else f'slave {slave_id}' + raise PS10Error(f'no reply from the {unit} to {command}') + return reply[:-len(TERMINATOR)].decode('ascii') + + def close(self): + if self._serial.is_open: + self._serial.close() + + +class AxisState(str, Enum): + """States returned by ?ASTAT (PS 10 manual, command set).""" + NOT_INITIALIZED = 'I' + DISABLED = 'O' + READY = 'R' + POSITIONING = 'T' + VELOCITY_MODE = 'V' + REFERENCE_RUN = 'P' + RELEASING_LIMIT_SWITCH = 'F' + STOPPED_AT_LIMIT_SWITCH = 'L' + STOPPED_AT_BRAKE_SWITCH = 'B' + LIMIT_SWITCH_ERROR = 'A' + MOTION_CONTROLLER_ERROR = 'M' + TIMEOUT = 'Z' + PHASE_INITIALIZATION = 'H' + NOT_ENABLED = 'U' + MOTION_ERROR = 'E' + UNKNOWN = '?' + + +MOVING_STATES = (AxisState.POSITIONING, AxisState.VELOCITY_MODE, + AxisState.REFERENCE_RUN, AxisState.RELEASING_LIMIT_SWITCH) + + +def slave_id_from_config(slave_id) -> int | None: + """None for the master ('master' in the configuration), the slave ID otherwise.""" + return None if slave_id == MASTER else int(slave_id) + +def steps_per_unit(pitch: float, gear_ratio: float, fullsteps_per_revolution: int, microsteps: int) -> float: + """Microsteps per mm (or per degree) of a stage driven by a stepper motor. + + The values are those shown by OWISoft in Control > Define positioning unit. + """ + return gear_ratio * fullsteps_per_revolution * microsteps / pitch + + +class PS10Axis: + """The single axis of one PS 10 unit, in physical units (mm or deg). + + Parameters + ---------- + bus: PS10Bus + the serial link shared by all the units + slave_id: int or None + None for the master, the slave ID otherwise + steps_per_unit: float + microsteps per mm (linear stage) or per degree (rotation stage) + """ + def __init__(self, bus: PS10Bus, slave_id, steps_per_unit: float): + self._bus = bus + self.slave_id = slave_id + self.steps_per_unit = steps_per_unit + + @classmethod + def from_config(cls, bus: PS10Bus, axis: dict) -> 'PS10Axis': + """Build an axis from one [[ps10.axes]] block of the configuration.""" + slave_id = slave_id_from_config(axis['slave_id']) + return cls(bus, slave_id, steps_per_unit(axis['pitch'], axis['gear_ratio'], + axis['fullsteps_per_revolution'], axis['microsteps'])) + + def init(self): + """Switch the axis on if needed and use absolute targets. + + INIT1 is sent only when the axis is not ready: on a PS 10 it also clears the validity of the + reference run (?REFST1), even on an axis that is already switched on. + """ + if self.state() != AxisState.READY: + self._bus.write(self.slave_id, 'INIT1') + self._bus.write(self.slave_id, 'ABSOL1') + + def state(self) -> AxisState: + """Current state of the axis, see AxisState.""" + reply = self._bus.query(self.slave_id, '?ASTAT') + try: + return AxisState(reply) + except ValueError: + raise PS10Error(f'unknown axis state {reply!r}') from None + + def is_moving(self) -> bool: + return self.state() in MOVING_STATES + + def get_position(self) -> float: + return int(self._bus.query(self.slave_id, '?CNT1')) / self.steps_per_unit + + def move_abs(self, position: float): + """Start a move to position; return without waiting for the end of the move.""" + steps = round(position * self.steps_per_unit) + self._bus.write(self.slave_id, f'PSET1={steps}') + self._bus.write(self.slave_id, 'PGO1') + + def stop(self): + self._bus.write(self.slave_id, 'STOP1') + + def reference(self, mode: int = 4): + """Start a reference run, REF1=mode in the PS 10 manual. + + Mode 4, used by OWISoft for these stages, approaches the reference switch, releases it and sets the + position to 0. The run ends when the axis is no longer moving. + """ + self._bus.write(self.slave_id, f'REF1={mode}') + + def is_referenced(self) -> bool: + """True after a successful reference run; reset when an open-loop stepper motor is switched off.""" + return self._bus.query(self.slave_id, '?REFST1') == '1' + + +class _SimulatedUnit: + """State of one simulated PS 10 unit.""" + + def __init__(self, velocity: int): + self.velocity = velocity # microsteps per second, as returned by ?PVEL1 + self.state = AxisState.DISABLED + self.absolute = False + self.target = 0 + self._start = 0 + self._end = 0 + self._start_time = 0. + self._duration = 0. + self.referenced = False + + def counter(self) -> int: + """Current position in microsteps; ends the move when its duration has elapsed.""" + if self.state in (AxisState.POSITIONING, AxisState.REFERENCE_RUN): + elapsed = time.perf_counter() - self._start_time + if elapsed < self._duration: + return round(self._start + (self._end - self._start) * elapsed / self._duration) + if self.state == AxisState.REFERENCE_RUN: + self.referenced = True + self.state = AxisState.READY + self._start = self._end + return self._start + + def reference(self): + start = self.counter() + self._start = start + self._end = 0 + self._start_time = time.perf_counter() + self._duration = abs(start) / self.velocity + self.state = AxisState.REFERENCE_RUN + + def stop(self): + self._start = self.counter() + if self.state in (AxisState.POSITIONING, AxisState.REFERENCE_RUN): + self.state = AxisState.READY + + def go(self): + start = self.counter() + self._start = start + self._end = self.target if self.absolute else start + self.target + self._start_time = time.perf_counter() + self._duration = abs(self._end - start) / self.velocity + self.state = AxisState.POSITIONING + + +class MockPS10Bus: + """Simulated PS 10 units with the same public methods as PS10Bus, used for tests and for port MOCK. + + Only the commands used by PS10Axis are simulated; any other one raises PS10Error. + """ + + def __init__(self, slave_ids=(None,), velocity: int = 25000): + self._units = {slave_id: _SimulatedUnit(velocity) for slave_id in slave_ids} + + def write(self, slave_id, command: str): + unit = self._units.get(slave_id) + if unit is None: + return # an absent unit does not react, as on the real bus + unit.counter() # update the state first + if command == 'INIT1': + unit.state = AxisState.READY + elif command == 'ABSOL1': + unit.absolute = True + elif command == 'RELAT1': + unit.absolute = False + elif command.startswith('PSET1='): + unit.target = int(command.split('=')[1]) + elif command == 'PGO1': + if unit.state == AxisState.READY: + unit.go() + elif command == 'STOP1': + unit.stop() + elif command.startswith('REF1='): + if unit.state == AxisState.READY: + unit.reference() + else: + raise PS10Error(f'{command} is not simulated') + + def query(self, slave_id, command: str) -> str: + unit = self._units.get(slave_id) + if unit is None: + unit_name = 'master' if slave_id is None else f'slave {slave_id}' + raise PS10Error(f'no reply from the {unit_name} to {command}') + position = unit.counter() + replies = {'?ASTAT': unit.state.value, + '?CNT1': str(position), + '?MODE1': 'ABSOL' if unit.absolute else 'RELAT', + '?PVEL1': str(unit.velocity), + '?VERSION': 'PS10-MOCK', + '?REFST1': '1' if unit.referenced else '0'} + if command not in replies: + raise PS10Error(f'{command} is not simulated') + return replies[command] + + def close(self): + pass diff --git a/src/pymodaq_plugins_owis/resources/config_template.toml b/src/pymodaq_plugins_owis/resources/config_template.toml index a2604a3..ec1d695 100644 --- a/src/pymodaq_plugins_owis/resources/config_template.toml +++ b/src/pymodaq_plugins_owis/resources/config_template.toml @@ -1,2 +1,29 @@ -title = 'this is the configuration file of the plugin XXX' +title = 'Configuration file of pymodaq_plugins_owis' +[ps10] +port = 'MOCK' # serial port of the master PS 10 (e.g. 'COM8'), MOCK for a simulated bus + +# One [[ps10.axes]] block per PS 10 unit, with the values shown by OWISoft in +# Control > Define positioning unit. slave_id is 'master' for the unit connected by USB, +# else its slave ID on the CANopen bus (Control > CANopen bus > Check hardware). + +[[ps10.axes]] +name = 'Z' +stage = 'HVM100N-30-HiSM' +slave_id = 'master' +units = 'mm' +pitch = 0.5 # units per revolution of the spindle (mm, or deg for a rotation stage) +gear_ratio = 1.0 +fullsteps_per_revolution = 200 +microsteps = 50 +home_position = 15 # position reached after the reference run, in the unit of the axis + +[[ps10.axes]] +name = "Theta" +stage = "DMT65-DM6-HSM" +slave_id = 2 +units = "degree" +pitch = 360.0 +gear_ratio = 180.0 +fullsteps_per_revolution = 200 +microsteps = 50 diff --git a/tests/test_owis_ps10.py b/tests/test_owis_ps10.py new file mode 100644 index 0000000..f11bbcf --- /dev/null +++ b/tests/test_owis_ps10.py @@ -0,0 +1,90 @@ +"""Tests of the OWIS PS 10 wrapper and plugin against the simulated bus (no hardware).""" +import pytest + +from pymodaq.utils.data import DataActuator +from pymodaq.utils.plugin_testing import make_actuator, move_abs_and_wait, move_home_and_wait, move_rel_and_wait +from pymodaq.utils.plugin_testing.harness import wait_for_signal + +from pymodaq_plugins_owis.daq_move_plugins.daq_move_OWIS_PS10 import AXES,DAQ_Move_OWIS_PS10 +from pymodaq_plugins_owis.hardware.ps10 import (AxisState, MockPS10Bus, PS10Axis, PS10Error, + slave_id_from_config, steps_per_unit) + + +# wrapper + +def test_steps_per_unit_of_the_stages(): + assert steps_per_unit(0.5, 1, 200, 50) == 20000 # HVM100N-30-HiSM + assert steps_per_unit(1, 1, 200, 50) == 10000 # LTM60-25-HSM + assert steps_per_unit(360, 180, 200, 50) == 5000 # DMT65-DM6-HSM + + +def test_slave_id_from_config(): + assert slave_id_from_config('master') is None + assert slave_id_from_config(3) == 3 + + +def test_absent_unit_raises(): + bus = MockPS10Bus(slave_ids=(None, 1)) + with pytest.raises(PS10Error): + bus.query(5, '?ASTAT') + + +def test_axis_does_not_move_before_init(): + axis = PS10Axis(MockPS10Bus(slave_ids=(1,)), slave_id=1, steps_per_unit=10000) + axis.move_abs(1.0) + assert axis.state() == AxisState.DISABLED + assert axis.get_position() == 0 + + +# plugin + +@pytest.fixture +def actuator(qapp): + actuator = make_actuator(DAQ_Move_OWIS_PS10, port='MOCK') + yield actuator + actuator.close() + + +def test_init(actuator): + assert actuator.initialized + assert isinstance(actuator.controller, MockPS10Bus) + + +def test_move_abs(actuator): + position = move_abs_and_wait(actuator, 0.5) + assert position.value(actuator.axis_unit) == pytest.approx(0.5, abs=actuator.epsilon) + + +def test_move_rel(actuator): + move_abs_and_wait(actuator, 0.5) + position = move_rel_and_wait(actuator, 0.25) + assert position.value(actuator.axis_unit) == pytest.approx(0.75, abs=actuator.epsilon) + + +def test_other_units_are_converted(actuator): + if actuator.axis_unit != 'mm': + pytest.skip('the first axis of the configuration is not in mm') + position = move_abs_and_wait(actuator, DataActuator(data=500., units='um')) + assert position.value('mm') == pytest.approx(0.5, abs=actuator.epsilon) + + +def test_stop_motion_ends_the_move(actuator): + def start_and_stop(): + actuator.move_abs(DataActuator(data=20., units=actuator.axis_unit)) + actuator.stop_motion() + + wait_for_signal(actuator.move_done_signal, start_and_stop) + assert actuator.get_actuator_value().value(actuator.axis_unit) < 20. + + +def test_slave_shares_the_bus_of_the_master(actuator): + slave = make_actuator(DAQ_Move_OWIS_PS10, controller=actuator.controller) + assert slave.initialized + assert slave.controller is actuator.controller + slave.close() + +def test_move_home_ends_at_home_position(actuator): + move_abs_and_wait(actuator, 0.5) + position = move_home_and_wait(actuator, timeout_ms=20000) + home = AXES[actuator.axis_index_key].get('home_position', 0.) + assert position.value(actuator.axis_unit) == pytest.approx(home, abs=actuator.epsilon)