diff --git a/README.rst b/README.rst index 3a26dbf..db2ffab 100644 --- a/README.rst +++ b/README.rst @@ -1,11 +1,11 @@ -pymodaq_plugins_alcatel +pymodaq_plugins_pfeiffer ######################## Authors ======= -* Titouan Gadeyne (titouan.gadeyne@cea.fr) - +* Titouan Gadeyne (titouan.gadeyne@cea.fr) for Alcatel driver +* Lucas Nicolas (lucas.nicolas@onera.fr) for OmniControl driver Instruments =========== @@ -16,12 +16,21 @@ Viewer0D ++++++++ * **ACM1000**: Alcatel ACM 1000 six-port gauge controller +* **OmniControl 200**: OmniControl 200 with pressure gauge connected (tested with PKR251) + -Installation instructions -========================= +Installation instructions for Alcatel plugins +============================================= * PyMoDAQ 4 * Windows 10 * No drivers from Alcatel are required. * Your PC should have serial ports (COM ports) to connect the controller. On Windows 10 you may need to install a driver to create virtual COM ports. + +Installation instructions for Pfeiffer plugins +============================================== + +* PyMoDAQ 5.0.x or later +* May require a virtual COM port driver: https://ftdichip.com/drivers/ + diff --git a/pyproject.toml b/pyproject.toml index f648361..2be7fdb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,11 +6,11 @@ h5exporters = false # true if plugin contains custom h5 file exporters scanners = false # true if plugin contains custom scan layout (daq_scan extensions) [urls] -package-url = "https://github.com/Titouan-Gadeyne/pymodaq_plugins_alcatel" +package-url = "https://github.com/PyMoDAQ/pymodaq_plugins_pfeiffer" [project] -name = "pymodaq_plugins_alcatel" -description = "PyMoDAQ plugin for the Alcatel ACM1000 6-port gauge controller." +name = "pymodaq_plugins_pfeiffer" +description = "PyMoDAQ plugin for the Pfeiffer/Alcatel instruments." dependencies = [ "pymodaq>=5.3.2", "pymodaq_utils>=5.3.1", diff --git a/src/pymodaq_plugins_alcatel/hardware/__init__.py b/src/__init__.py similarity index 100% rename from src/pymodaq_plugins_alcatel/hardware/__init__.py rename to src/__init__.py diff --git a/src/pymodaq_plugins_alcatel/daq_viewer_plugins/__init__.py b/src/pymodaq_plugins_alcatel/daq_viewer_plugins/__init__.py deleted file mode 100644 index b28b04f..0000000 --- a/src/pymodaq_plugins_alcatel/daq_viewer_plugins/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/pymodaq_plugins_alcatel/resources/config_template.toml b/src/pymodaq_plugins_alcatel/resources/config_template.toml deleted file mode 100644 index 3736213..0000000 --- a/src/pymodaq_plugins_alcatel/resources/config_template.toml +++ /dev/null @@ -1,2 +0,0 @@ -#this is the configuration file of the plugin - diff --git a/src/pymodaq_plugins_alcatel/__init__.py b/src/pymodaq_plugins_pfeiffer/__init__.py similarity index 75% rename from src/pymodaq_plugins_alcatel/__init__.py rename to src/pymodaq_plugins_pfeiffer/__init__.py index fe752d3..9b1abfe 100644 --- a/src/pymodaq_plugins_alcatel/__init__.py +++ b/src/pymodaq_plugins_pfeiffer/__init__.py @@ -1,11 +1,13 @@ -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: __version__ = '0.0.0dev' + + + diff --git a/src/pymodaq_plugins_alcatel/resources/__init__.py b/src/pymodaq_plugins_pfeiffer/app/__init__.py similarity index 100% rename from src/pymodaq_plugins_alcatel/resources/__init__.py rename to src/pymodaq_plugins_pfeiffer/app/__init__.py diff --git a/src/pymodaq_plugins_alcatel/daq_move_plugins/__init__.py b/src/pymodaq_plugins_pfeiffer/daq_move_plugins/__init__.py similarity index 96% rename from src/pymodaq_plugins_alcatel/daq_move_plugins/__init__.py rename to src/pymodaq_plugins_pfeiffer/daq_move_plugins/__init__.py index 95cce4d..7f92eb0 100644 --- a/src/pymodaq_plugins_alcatel/daq_move_plugins/__init__.py +++ b/src/pymodaq_plugins_pfeiffer/daq_move_plugins/__init__.py @@ -9,4 +9,5 @@ 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/__init__.py b/src/pymodaq_plugins_pfeiffer/daq_viewer_plugins/__init__.py similarity index 100% rename from __init__.py rename to src/pymodaq_plugins_pfeiffer/daq_viewer_plugins/__init__.py diff --git a/src/pymodaq_plugins_alcatel/daq_viewer_plugins/plugins_0D/__init__.py b/src/pymodaq_plugins_pfeiffer/daq_viewer_plugins/plugins_0D/__init__.py similarity index 100% rename from src/pymodaq_plugins_alcatel/daq_viewer_plugins/plugins_0D/__init__.py rename to src/pymodaq_plugins_pfeiffer/daq_viewer_plugins/plugins_0D/__init__.py diff --git a/src/pymodaq_plugins_alcatel/daq_viewer_plugins/plugins_0D/daq_0Dviewer_ACM1000.py b/src/pymodaq_plugins_pfeiffer/daq_viewer_plugins/plugins_0D/daq_0Dviewer_ACM1000.py similarity index 98% rename from src/pymodaq_plugins_alcatel/daq_viewer_plugins/plugins_0D/daq_0Dviewer_ACM1000.py rename to src/pymodaq_plugins_pfeiffer/daq_viewer_plugins/plugins_0D/daq_0Dviewer_ACM1000.py index af94dd3..263720e 100644 --- a/src/pymodaq_plugins_alcatel/daq_viewer_plugins/plugins_0D/daq_0Dviewer_ACM1000.py +++ b/src/pymodaq_plugins_pfeiffer/daq_viewer_plugins/plugins_0D/daq_0Dviewer_ACM1000.py @@ -5,7 +5,7 @@ from pymodaq.utils.parameter import Parameter import pylablib as pylablib -from pymodaq_plugins_alcatel.hardware.ACM1000_wrapper import ACM1000 +from pymodaq_plugins_pfeiffer.hardware.ACM1000_wrapper import ACM1000 class DAQ_0DViewer_ACM1000(DAQ_Viewer_base): diff --git a/src/pymodaq_plugins_pfeiffer/daq_viewer_plugins/plugins_0D/daq_0Dviewer_Pfeiffer_Omnicontrol.py b/src/pymodaq_plugins_pfeiffer/daq_viewer_plugins/plugins_0D/daq_0Dviewer_Pfeiffer_Omnicontrol.py new file mode 100644 index 0000000..80e606f --- /dev/null +++ b/src/pymodaq_plugins_pfeiffer/daq_viewer_plugins/plugins_0D/daq_0Dviewer_Pfeiffer_Omnicontrol.py @@ -0,0 +1,132 @@ +import numpy as np + +from pymodaq_utils.utils import ThreadCommand +from pymodaq_data.data import DataToExport +from pymodaq_gui.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_plugins_pfeiffer.hardware.omnicontrol import Omnicontrol +from serial.tools import list_ports + +def get_com_ports() -> list[str]: + """Détecte les ports COM connectés et les renvoie sous forme de liste de strings.""" + return [port.device for port in list_ports.comports()] + +class DAQ_0DViewer_Pfeiffer_Omnicontrol(DAQ_Viewer_base): + """ Instrument plugin class for a OD viewer. + * Plugin for OmniControl 200 controller. + * Developed and tested only with a PKR 251 pressure gauge connected. + * Developed on PyMoDAQ 5.2 + * May require a virtual COM port driver: https://ftdichip.com/drivers/ + + """ + params = comon_parameters+[ + {'title': 'COM port :', 'name': 'com_port', 'type': 'list', 'limits': get_com_ports()}, + {'title': 'Channel 1', 'name': 'ch_1', 'type': 'bool', 'value':True}, + {'title': 'Channel 2', 'name': 'ch_2', 'type': 'bool', 'value':True}, + ] + + def _active_channels(self): + """Names of the currently checked channel booleans, in tree order.""" + return [ch.name() + for ch in self.settings.children() + if ch.name().startswith('ch_') and ch.value()] + + + def ini_attributes(self): + self.controller: Omnicontrol = None + self.port=None + pass + + def ini_detector(self, controller=None): + """Detector communication initialization""" + self.settings.child('com_port').setLimits(get_com_ports()) + if self.is_master: + self.port=self.settings.child('com_port').value() + self.port="COM9" + self.controller = Omnicontrol(self.port) + initialized = True + else: + self.controller = controller + initialized = True + + self.pressure_data=[np.array([0]) for ch in self._active_channels()] + label=[] + for ch in self._active_channels(): + if ch == 'ch_1': + label.append('Channel 1') + elif ch == 'ch_2': + label.append('Channel 2') + self.dte_signal_temp.emit(DataToExport(name='OmniControl', + data=[DataFromPlugins(name='Pressure', + data=self.pressure_data, + dim='Data0D', + labels=label)])) + # labels = ['Channel 1', 'Channel 2'])])) + + info = self.controller.read_name() # lève PfeifferError si pas de réponse + return info, initialized + + def close(self): + """Terminate the communication protocol""" + if self.is_master and self.controller is not None: + self.controller.close() + self.controller = None + + def grab_data(self, Naverage=1, **kwargs): + """Start a grab from the detector + + Parameters + ---------- + Naverage: int + Number of hardware averaging (if hardware averaging is possible, self.hardware_averaging should be set to + True in class preamble and you should code this implementation) + kwargs: dict + others optionals arguments + """ + pressure_data=[] + try: + for ch in self._active_channels(): + if ch == 'ch_1': + pressure_data.append(np.array([self.controller.read_pressure(122)])) + elif ch == 'ch_2': + pressure_data.append(np.array([self.controller.read_pressure(132)])) + except Exception as e: + self.emit_status(ThreadCommand('Update_Status', [str(e), 'log'])) + return + + label=[] + for ch in self._active_channels(): + if ch == 'ch_1': + label.append('Channel 1') + elif ch == 'ch_2': + label.append('Channel 2') + + self.dte_signal.emit(DataToExport( + name='OmniControl', + data=[DataFromPlugins(name='Pressure', + data=pressure_data, + dim='Data0D', + labels=label)])) + + def stop(self): + """Stop the current grab hardware wise if necessary""" + 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 + """ + ## TODO for your custom plugin + if param.name() == "com_port": + self.port=self.settings.child('com_port').value() + + +if __name__ == '__main__': + main(__file__) diff --git a/src/pymodaq_plugins_alcatel/daq_viewer_plugins/plugins_1D/__init__.py b/src/pymodaq_plugins_pfeiffer/daq_viewer_plugins/plugins_1D/__init__.py similarity index 90% rename from src/pymodaq_plugins_alcatel/daq_viewer_plugins/plugins_1D/__init__.py rename to src/pymodaq_plugins_pfeiffer/daq_viewer_plugins/plugins_1D/__init__.py index 19e5b12..2eea9e6 100644 --- a/src/pymodaq_plugins_alcatel/daq_viewer_plugins/plugins_1D/__init__.py +++ b/src/pymodaq_plugins_pfeiffer/daq_viewer_plugins/plugins_1D/__init__.py @@ -1,6 +1,7 @@ import importlib from pathlib import Path -from ... import set_logger +from pymodaq_utils.logger import set_logger + logger = set_logger('viewer1D_plugins', add_to_console=False) for path in Path(__file__).parent.iterdir(): diff --git a/src/pymodaq_plugins_alcatel/daq_viewer_plugins/plugins_2D/__init__.py b/src/pymodaq_plugins_pfeiffer/daq_viewer_plugins/plugins_2D/__init__.py similarity index 88% rename from src/pymodaq_plugins_alcatel/daq_viewer_plugins/plugins_2D/__init__.py rename to src/pymodaq_plugins_pfeiffer/daq_viewer_plugins/plugins_2D/__init__.py index 4aa03f3..661c5e5 100644 --- a/src/pymodaq_plugins_alcatel/daq_viewer_plugins/plugins_2D/__init__.py +++ b/src/pymodaq_plugins_pfeiffer/daq_viewer_plugins/plugins_2D/__init__.py @@ -1,6 +1,6 @@ import importlib from pathlib import Path -from ... import set_logger +from pymodaq_utils.logger import set_logger logger = set_logger('viewer2D_plugins', add_to_console=False) for path in Path(__file__).parent.iterdir(): @@ -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_alcatel/daq_viewer_plugins/plugins_ND/__init__.py b/src/pymodaq_plugins_pfeiffer/daq_viewer_plugins/plugins_ND/__init__.py similarity index 90% rename from src/pymodaq_plugins_alcatel/daq_viewer_plugins/plugins_ND/__init__.py rename to src/pymodaq_plugins_pfeiffer/daq_viewer_plugins/plugins_ND/__init__.py index 6f1c625..fa5e237 100644 --- a/src/pymodaq_plugins_alcatel/daq_viewer_plugins/plugins_ND/__init__.py +++ b/src/pymodaq_plugins_pfeiffer/daq_viewer_plugins/plugins_ND/__init__.py @@ -1,6 +1,6 @@ import importlib from pathlib import Path -from ... import set_logger +from pymodaq_utils.logger import set_logger logger = set_logger('viewerND_plugins', add_to_console=False) for path in Path(__file__).parent.iterdir(): diff --git a/src/pymodaq_plugins_alcatel/models/__init__.py b/src/pymodaq_plugins_pfeiffer/exporters/__init__.py similarity index 100% rename from src/pymodaq_plugins_alcatel/models/__init__.py rename to src/pymodaq_plugins_pfeiffer/exporters/__init__.py diff --git a/src/pymodaq_plugins_alcatel/extensions/__init__.py b/src/pymodaq_plugins_pfeiffer/extensions/__init__.py similarity index 95% rename from src/pymodaq_plugins_alcatel/extensions/__init__.py rename to src/pymodaq_plugins_pfeiffer/extensions/__init__.py index d6a0339..180d4dd 100644 --- a/src/pymodaq_plugins_alcatel/extensions/__init__.py +++ b/src/pymodaq_plugins_pfeiffer/extensions/__init__.py @@ -3,4 +3,4 @@ Created the 01/06/2023 @author: Sebastien Weber -""" \ No newline at end of file +""" diff --git a/src/pymodaq_plugins_alcatel/hardware/ACM1000_wrapper.py b/src/pymodaq_plugins_pfeiffer/hardware/ACM1000_wrapper.py similarity index 100% rename from src/pymodaq_plugins_alcatel/hardware/ACM1000_wrapper.py rename to src/pymodaq_plugins_pfeiffer/hardware/ACM1000_wrapper.py diff --git a/src/pymodaq_plugins_pfeiffer/hardware/__init__.py b/src/pymodaq_plugins_pfeiffer/hardware/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/pymodaq_plugins_pfeiffer/hardware/omnicontrol.py b/src/pymodaq_plugins_pfeiffer/hardware/omnicontrol.py new file mode 100644 index 0000000..63cc84a --- /dev/null +++ b/src/pymodaq_plugins_pfeiffer/hardware/omnicontrol.py @@ -0,0 +1,287 @@ +""" +omnicontrol_driver.py - Read and control a Pfeiffer Vacuum OmniControl over RS-458 + +Implements the "Pfeiffer Vacuum protocol for RS-458 interface" as documented +in the OmniControl Communication Guid. + +Serial line settings are fixed by the protocol: + 9600 baud, 8 data bits, no parity, 1 stop bit. + +Telegram frame: + + a2 a1 a0 * 0 n2 n1 n0 l1 l0 dn...d0 c2 c1 c0 CR + \_____/ \_/ \____/ \_/ \____/ \____/ + address act param.No length data checksum + + The action digit is either '0' (read) or '1' (write) + +IMPORTANT: + * The OmniControl should be in "device mode" for this code to work. + => (4 rectangles in the bottom left corner) -> settings -> RS-458 -> device mode + (You can also check that the default address of the OmniControl is still '101') + + * The OmniControl class should always be closed after its usage in order to + free the port for later usage (for example: 'with OmniControl(PORT) as dev:'). + +Requires: pyserial +""" + +import serial +import math +from dataclasses import dataclass + +CR = b'\r' +ERROR_PAYLOADS = {"NO_DEF", "_RANGE", '_LOGIC'} + +class PfeifferError(Exception): + """Raised on a protocol-level error reply or a malformed/failed telegram""" + + +# --------------------------------------------------------------------------------------------- # +# Data types +# --------------------------------------------------------------------------------------------- # + +# Each entry: (length, decode(raw_str), decode(raw_str) -> value, encode(value) -> raw_str) + +def _enc_bool_old(v): return "111111" if v else "000000" +def _dec_bool_old(s): return s == "111111" + +def _enc_uint(v): return f"{int(v):06d}" +def _dec_uint(s): return int(s) + +def _enc_ureal(v): return f"{int(round(float(v) * 100)):06d}" +def _dec_ureal(s): return int(s) / 100.0 + +def _enc_str(v): return f"{str(v):<6.6s}" +def _dec_str(s): return s.strip() + +def _enc_bool_new(v): return "1" if v else "0" +def _dec_bool_new(s): return s == "1" + +def _enc_ushort(v): return f"{int(v):03d}" +def _dec_ushort(s): return int(s) + +def _enc_str16(v): return f"{str(v):<16.6s}" + +def _enc_str8(v): return f"{str(v):<8.8s}" + +def _enc_expo(v): + v = float(v) + + if v <= 0: return "000000" + + exponent = math.floor(math.log10(v)) + mantissa = round(v / (10.0 ** exponent) * 1000) + if mantissa >= 10000: + mantissa //= 10 + exponent += 1 + code = exponent + 20 + if not 0 <= code <= 99: + raise PfeifferError(f"value {v!r} out of u_expo_new range") + return f"{mantissa:04d}{code:02d}" + +def _dec_expo(s): + # "100023" -> mantissa 1000 (=> 1.000), exponent 23-20 = 3 => 1.0e3 + mantissa = int(s[:4]) / 1000.0 + exponent = int(s[4:]) - 20 + return mantissa * (10.0 ** exponent) + +@dataclass(frozen=True) +class DataType: + code: int + length: int + decode: callable + encode: callable + name: str + +DATA_TYPES = { + 0: DataType(0, 6, _dec_bool_old, _enc_bool_old, "boolean_old"), + 1: DataType(1, 6, _dec_uint, _enc_uint, "u_integer"), + 2: DataType(2,6, _dec_ureal, _enc_ureal, "u_real"), + 4: DataType(4,6, _dec_str, _enc_str, "string"), + 6: DataType(6,1, _dec_bool_new, _enc_bool_new, "boolean_new"), + 7: DataType(7,3, _dec_ushort, _enc_ushort, "u_short_int"), + 10: DataType(10, 6, _dec_expo, _enc_expo, "u_expo_new"), + 11: DataType(11, 16, _dec_str, _enc_str16, "string16"), + 12: DataType(12, 8, _dec_str, _enc_str8, "string8") +} + +# --------------------------------------------------------------------------------------------- # +# Parameter registery +# --------------------------------------------------------------------------------------------- # + +@dataclass(frozen=True) +class Parameter: + number: int + type_code: int + access: str + unit: str + description: str + +PARAMETERS: dict[str, Parameter] = { + # --- Control commands --- + "DeGas": Parameter(40, 6, "RW", "", "Clean measuring element"), + "Sens OnOff": Parameter(41, 7, "RW", "", "Switch BA/CC or the cold cathode on/off"), + "DirDigOut": Parameter(70, 1, "RW", "", "Digital outputs (per-digit set/reset/keep)"), + "DirRelOut": Parameter(71, 1, "RW", "", "Relay outputs (per-digit set/reset/keep"), + # --- Status requests --- + "ErrorCode": Parameter(303, 4, "R", "", "Error code"), + "FWversion": Parameter(312, 4, "R", "", "Firmware Version"), + "ElecName": Parameter(349, 4, "R", "", "Device designation"), + "HWversion": Parameter(352, 4, "R", "", "Hardware version"), + "SerialNo": Parameter(355, 11, "R", "", "Serial number"), + "DirDigInp": Parameter(386, 1, "R", "", "Digital inputs (set/reset/keep)"), + "DirAlgInp": Parameter(387, 2, "R", "", "Analog input"), + "OrderCode": Parameter(388, 11, "R", "", "Order number"), + # --- Set value settings --- + "DirAlgOut": Parameter(727, 2, "RW", "V", "Analog output"), + "Pressure": Parameter(740, 10, "RW", "hPa", "Pressure value"), + "UserGasCor": Parameter(742, 2, "RW", "", "Correction factor"), + "BaseAdr": Parameter(797, 1, "RW", "", "Interface address"), +} + +# --------------------------------------------------------------------------------------------- # +# Telegram building / parsing +# --------------------------------------------------------------------------------------------- # + +def _checksum(payload: str) -> str: + return f"{sum(ord(c) for c in payload)%256:03d}" + +def build_telegram(address: int, action: str, number: int, data:str) -> bytes: + """Assemble one telegram.""" + if not 0 <= address <= 999: + raise ValueError("address must be between 0 and 999") + if action not in ("0", "1"): + raise ValueError("action must be '0' (read) or '1' (write)") + body = f"{address:03d}{action}0{number:03d}{len(data):02d}{data}" + return (body + _checksum(body)).encode("ascii") + CR + +def parse_response(raw: bytes) -> tuple[int, int, str]: + """Validate a reply and return (address, parameter_number, data_field).""" + if not raw: + raise PfeifferError("no response (timeout) - check wiring, address, baud rate") + text = raw.rstrip(b"\r\n").decode("ascii", errors="replace") + received_cksum = text[-3:] + body = text[:-3] + + if int(_checksum(body)) != int(received_cksum): + raise PfeifferError(f"checksum mismatch in reply: {text!r}") + + address = int(body[:3]) + number = int(body[5:8]) + length = int(body[8:10]) + data = body[10:10+length] + + if data in ERROR_PAYLOADS: + msg = { + "NO_DEF": "parameter does not exist", + "_RANGE": "value out of permissible range", + "_LOGIC": "logical access error (e.g. read-only parameter written)" + }[data] + raise PfeifferError(f"device error on parameter {number}: {data} ({msg})") + + return address, number, data + +# --------------------------------------------------------------------------------------------- # +# Main driver +# --------------------------------------------------------------------------------------------- # +class Omnicontrol: + """Talk to OmniControl or a unit on its RS-485 bus""" + + def __init__(self, port: str, address: int = 101, timeout: float = 0.5): + self.address = address + self.ser = serial.Serial( + port=port, + baudrate=9600, + parity=serial.PARITY_NONE, + stopbits=serial.STOPBITS_ONE, + timeout=timeout, + ) + + def _transact(self, action:str, number: int, data:str, address: int | None = None) -> str | None: + """Low level interaction with the device""" + addr = self.address if address is None else address + telegram = build_telegram(addr, action, number, data) + self.ser.reset_input_buffer() + self.ser.write(telegram) + self.ser.flush() + # Group ("9xx") and global ("100") addresses are not answered + if addr == 0 or 900 <= addr <= 999: + return None + reply = self.ser.read_until(CR) + _, _, field = parse_response(reply) + return field + + # --- generic read / write --- + + def read(self, parameter, address: int | None = None): + """Read a parameter, a parameter is either a registery name or (number, type_code)""" + number, data_type = self._resolve(parameter) + raw = self._transact('0', number, '=?', address) + return data_type.decode(raw) + + def write(self, parameter, value, address: int | None = None): + """Write a parameter, a parameter is either a registery name of (number, type_code)""" + number, data_type = self._resolve(parameter) + raw = self._transact("1", number, value, address) + return data_type.decode(raw) if raw is not None else None + + @staticmethod + def _resolve(parameter) -> tuple[int, DataType]: + if isinstance(parameter, str): + if parameter not in PARAMETERS: + raise KeyError(f"unknown parameter: {parameter!r};" + f"use one of {sorted(PARAMETERS)}" + f"or pass (number, type_code)") + p = PARAMETERS[parameter] + return p.number, DATA_TYPES[p.type_code] + number, type_code = parameter + if type_code not in DATA_TYPES: + raise ValueError("unknown data type code {type_code}") + return int(number), DATA_TYPES[type_code] + + # --- convenience for documented parameters --- + + def read_pressure(self, address=None) -> float: + """Read pressure in hPa (mbar).""" + pressure = self.read("Pressure", address) + if pressure > 2000: + raise OverflowError("the pressure is outside of the gauge range") + return pressure + + def read_error_code(self, address=None) -> str: + return self.read("ErrorCode", address) + + def read_firmware(self, address=None) -> str: + return self.read("FWversion", address) + + def read_name(self, address=None) -> str: + return self.read("ElecName", address) + + def read_serial(self, address=None) -> str: + return self.read("SerialNo", address) + + def device_info(self, address=None) -> str: + info = {} + for key, method in (("name", self.read_name), + ("firmware", self.read_firmware), + ("hardware", lambda a=address: self.read("HWversion", a)), + ("serial", self.read_serial), + ("order_code", lambda a=address: self.read("OrderCode", a)), + ("error", self.read_error_code)): + try: + info[key] = method(address) if callable(method) else method + except PfeifferError as exc: + info[key] = f"<{exc}>" + return str(info) + + # --- context manager / cleanup --- + + def close(self): + self.ser.close() + + def __enter__(self): + return self + + def __exit__(self, *exc): + self.close() \ No newline at end of file diff --git a/src/pymodaq_plugins_pfeiffer/models/__init__.py b/src/pymodaq_plugins_pfeiffer/models/__init__.py new file mode 100644 index 0000000..be002a9 --- /dev/null +++ b/src/pymodaq_plugins_pfeiffer/models/__init__.py @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +""" +Models of the extensions (PID, optimizers, DataMixer, Sequencer...) provided by this plugin package, one model per +module. Empty on purpose: see the section "Models of the extensions" of AGENTS.md and set models = true in the +[features] table of pyproject.toml once you add one. +""" diff --git a/src/pymodaq_plugins_pfeiffer/resources/__init__.py b/src/pymodaq_plugins_pfeiffer/resources/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/pymodaq_plugins_pfeiffer/resources/config_template.toml b/src/pymodaq_plugins_pfeiffer/resources/config_template.toml new file mode 100644 index 0000000..a2604a3 --- /dev/null +++ b/src/pymodaq_plugins_pfeiffer/resources/config_template.toml @@ -0,0 +1,2 @@ +title = 'this is the configuration file of the plugin XXX' + diff --git a/src/pymodaq_plugins_pfeiffer/scanners/__init__.py b/src/pymodaq_plugins_pfeiffer/scanners/__init__.py new file mode 100644 index 0000000..180d4dd --- /dev/null +++ b/src/pymodaq_plugins_pfeiffer/scanners/__init__.py @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +""" +Created the 01/06/2023 + +@author: Sebastien Weber +""" diff --git a/src/pymodaq_plugins_alcatel/utils.py b/src/pymodaq_plugins_pfeiffer/utils.py similarity index 88% rename from src/pymodaq_plugins_alcatel/utils.py rename to src/pymodaq_plugins_pfeiffer/utils.py index 1f225ab..4981b95 100644 --- a/src/pymodaq_plugins_alcatel/utils.py +++ b/src/pymodaq_plugins_pfeiffer/utils.py @@ -6,7 +6,7 @@ """ from pathlib import Path -from pymodaq.utils.config import BaseConfig, USER +from pymodaq_utils.config import BaseConfig, USER class Config(BaseConfig):