diff --git a/docs/conf.py b/docs/conf.py index f5be7c9..ac5c663 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -87,6 +87,15 @@ autodoc_mock_imports = [ "pandas", "scipy", "matplotlib", + # escape (SwissFEL's data-analysis package) transitively pulls in + # dask -> xarray, whose xarray/core/types.py defines a module-level + # `pd.Timestamp | datetime.datetime | ...` type alias evaluated eagerly + # at import time -- with `pandas` mocked above, that `|` on a mock + # object raises TypeError and takes down autodoc for every module in + # eco that imports escape transitively (eco.elements.assembly among + # them, via eco.acquisition.scan_data). Mocking escape itself avoids + # ever reaching xarray's import at all. + "escape", ] # -- MyST (Markdown) --------------------------------------------------------- diff --git a/docs/images/widget_indicator_gadgets_qt_simple.png b/docs/images/widget_indicator_gadgets_qt_simple.png new file mode 100644 index 0000000..add86ef Binary files /dev/null and b/docs/images/widget_indicator_gadgets_qt_simple.png differ diff --git a/docs/index.rst b/docs/index.rst index 96554bd..e60774b 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -76,7 +76,8 @@ scientific Python libraries. :link-type: doc The default Adjustable/Detector row in Qt vs ipywidgets, and the - LED/gauge/dial "indicator" gadgets on both. + matched, stock-widget-only LED/gauge/dial "indicator" gadgets on + both. .. grid-item-card:: :octicon:`stack` Widget containers :link: widget_containers diff --git a/docs/widget_views.md b/docs/widget_views.md index 4b1c7c7..d225b35 100644 --- a/docs/widget_views.md +++ b/docs/widget_views.md @@ -51,61 +51,38 @@ steps, or in-flight move stopping. ## Indicator / gadget widgets For a LabVIEW-style live panel — LEDs, gauges, dials — instead of a grid row, -eco provides small standalone gadgets, one per item: a richer Qt version and a -first-pass, stock-`ipywidgets` browser version. +eco provides small standalone gadgets, one per item. The current direction is +a **matched, as-simple-as-possible pair**, one module per backend, both built +entirely from each toolkit's own stock controls (no new dependency, no +custom-painted graphics) and sharing the same function names/signatures so +either is a drop-in for the other: -### Qt (`eco.widgets.indicator_widgets`) +- {py:mod}`eco.widgets.indicator_widgets_ipy` — ipywidgets (`lab`/`voila`) +- `eco.widgets.indicator_widgets_qt_simple` — Qt desktop -`eco.widgets.indicator_widgets` provides gadgets meant to be pulled out of -the property grid and dropped onto a -{py:class}`~eco.widgets.dashboard_qt.Dashboard`: +![The seven stock-ipywidgets gadgets: a green LED-styled Button for shutter_open, a vertical FloatProgress for pressure, a horizontal FloatProgress standing in for the needle gauge on energy, a FloatProgress showing intensity's position within its observed min/max as a strip-chart stand-in, a large HTML number for counts, a row of ToggleButtons for mode's enum choices, and a FloatSlider for position.](images/widget_indicator_gadgets_ipy.png) -![Five indicator gadgets against dummy items: a green LED for a boolean shutter state, a vertical bar gauge for a pressure Detector, a semicircular analog gauge with a needle for an energy readback, a rotary Dial in enum "mode-select" form showing every choice (standby/ready/running/fault) around the ring, and a horizontal Slider with a numeric readout for a position Adjustable.](images/widget_indicator_gadgets_qt.png) +*ipywidgets — `eco.widgets.indicator_widgets_ipy`* -| Gadget | Read/write | Notes | -|---|---|---| -| `LEDIndicator` | writes (click to toggle) if settable | green/red/gray for on/off/unknown; `threshold=` for "value ≥ X" | -| `BarGauge` | read-only | vertical or horizontal fill against `[vmin, vmax]` | -| `AnalogGauge` | read-only | semicircular needle gauge | -| `StripChart` | read-only | rolling line plot of the last N readings | -| `NumericTile` | read-only | large numeric readout + sparkline (KPI-tile style) | -| `Dial` | writes if settable | continuous rotary knob for plain numerics; a mode-select ring (every enum choice shown at once) when the item exposes `enum_strs` | -| `Slider` | writes if settable | horizontal slider with numeric readout | +![The same seven gadgets on the Qt side, built from plain QWidgets: a green circular QPushButton for shutter_open, a vertical QProgressBar for pressure, a horizontal QProgressBar for energy, a QProgressBar plus a "value [lo .. hi]" label for intensity, a large QLabel for counts, a row of checkable QPushButtons for mode's enum choices, and a QSlider for position.](images/widget_indicator_gadgets_qt_simple.png) -No dropdown, text entry, or hidden menu is needed to read a value at a -glance — that's the point of these versus the default grid row. Getting one -onto screen is a right-click away: right-click a parameter's name in the -normal Qt property grid → **Add indicator** → pick a gadget kind (see -`eco.widgets.display_qt`'s `_build_row`, wired via -`eco.widgets.indicator_widgets.attach_indicator_menu`). A gadget is also a -valid Qt Designer "promoted widget", and round-trips through a saved -dashboard layout via the item's alias path. +*Qt — `eco.widgets.indicator_widgets_qt_simple`* -### ipywidgets (`eco.widgets.indicator_widgets_ipy`) +| Gadget (same name, both modules) | ipywidgets control | Qt control | Notes | +|---|---|---|---| +| `led_indicator` | `Button` (`button_style`) | `QPushButton` (stylesheet) | click to toggle if settable; a plain label/HTML can't take a click back | +| `bar_gauge` | `FloatProgress` | `QProgressBar` | vertical or horizontal fill against `[vmin, vmax]` | +| `analog_gauge` | `FloatProgress` (horizontal) | `QProgressBar` (horizontal) | **approximation** — no needle; see below | +| `strip_chart` | `FloatProgress` + label | `QProgressBar` + label | **approximation** — position within the min/max seen so far, not a rolling line; see below | +| `numeric_tile` | `HTML` | `QLabel` (enlarged font) | large number, no sparkline (same reasoning as `strip_chart`) | +| `dial` | `ToggleButtons` (enum) / `FloatSlider` (numeric) | checkable `QPushButton` row (enum) / `QSlider` (numeric) | enum case shows every choice at once; dragging a value in a circle isn't idiomatic UX on either toolkit, so the numeric case reuses the slider rather than faking a knob | +| `slider` | `FloatSlider` | `QSlider` | writes on release if settable | -A first pass at the same seven gadgets for the `lab`/`voila` front ends, -built **entirely from stock ipywidgets controls** rather than a new -charting/gauge library — "something that works" now, not a redraw of the Qt -look: - -![The same seven gadgets, built from stock ipywidgets: a green LED-styled Button for shutter_open, a vertical FloatProgress for pressure, a horizontal FloatProgress standing in for the needle gauge on energy, a FloatProgress showing intensity's position within its observed min/max as a strip-chart stand-in, a large HTML number for counts, a row of ToggleButtons for mode's enum choices, and a FloatSlider for position.](images/widget_indicator_gadgets_ipy.png) - -| Gadget | Stock control used | Notes | -|---|---|---| -| `led_indicator` | `Button` (`button_style`) | a plain `HTML` div can't take a click back from the browser, so this is a styled Button, not a bare circle | -| `bar_gauge` | `FloatProgress` | vertical or horizontal, exact match to the Qt bar gauge | -| `analog_gauge` | `FloatProgress` (horizontal) | **approximation** — no needle; see below | -| `strip_chart` | `FloatProgress` + label | **approximation** — shows position within the min/max seen so far, not a rolling line; see below | -| `numeric_tile` | `HTML` | large number, no sparkline (same reasoning as `strip_chart`) | -| `dial` | `ToggleButtons` (enum) or `FloatSlider` (numeric) | enum case matches the Qt "every choice visible" idea, laid out as buttons instead of a ring; dragging a value around a circle isn't idiomatic web UX, so the numeric case reuses the slider rather than faking a knob | -| `slider` | `FloatSlider` | exact match to the Qt slider | - -Five of the seven are exact stock-widget matches. The other two +Five of the seven are exact stock-widget matches on both sides. The other two (`analog_gauge`, `strip_chart`) are deliberately left as plain bar/value -approximations rather than reaching for a new dependency — see -`eco.widgets.indicator_widgets_ipy`'s module docstring. If a real needle -gauge or a real rolling plot is wanted later, the candidates worth reviewing -first: +approximations rather than reaching for a new dependency — see either +module's docstring. If a real needle gauge or a real rolling plot is wanted +later, the candidates worth reviewing first: - **Plotly `go.Indicator`** (`mode="gauge+number"` for the needle gauge, `mode="number+delta"` for a nicer KPI tile) — its `FigureWidget` is a real @@ -125,6 +102,25 @@ first: widget, if a literal LabVIEW look is ever wanted beyond what the above give. Worth knowing about, not needed for anything on this page. -There's no "Add indicator" menu for the ipywidgets side yet (there's no -natural right-click-a-label hook the way Qt has one) — call the function -directly, e.g. `eco.widgets.indicator_widgets_ipy.bar_gauge(my_assembly.pressure, vmin=0, vmax=100)`. +Neither module has a discovery UI yet ("right-click a name → add gadget" on +Qt, or an equivalent on the notebook side) — call the function directly for +now, e.g. `eco.widgets.indicator_widgets_ipy.bar_gauge(my_assembly.pressure, vmin=0, vmax=100)` +or the equivalent `eco.widgets.indicator_widgets_qt_simple.bar_gauge(...)`. + +### The older, hand-painted Qt gadgets + +`eco.widgets.indicator_widgets` — the original, richer Qt-only module (real +needle gauge, a radial mode-select dial face, a live rolling strip-chart) — +still exists and is unrelated to the simple pair above, not superseded by +it. It's wired into the desktop app's right-click **"Add indicator"** menu +and a droppable {py:class}`~eco.widgets.dashboard_qt.Dashboard`, and its +gadgets double as valid Qt Designer "promoted widgets": + +![Five hand-painted indicator gadgets against dummy items: a green LED for a boolean shutter state, a vertical bar gauge for a pressure Detector, a semicircular analog gauge with a needle for an energy readback, a rotary Dial in enum "mode-select" form showing every choice (standby/ready/running/fault) around the ring, and a horizontal Slider with a numeric readout for a position Adjustable.](images/widget_indicator_gadgets_qt.png) + +See its module docstring for the full gadget list and +`eco.widgets.indicator_widgets.attach_indicator_menu` for how it's wired +into `eco.widgets.display_qt`'s property grid. Reach for this one if the +simple pair's two approximations (no needle, no rolling line) actually +matter for a given panel; otherwise the matched simple pair above is the +current default recommendation for new work, on either backend. diff --git a/eco/devices_general/vacuum/gauges.py b/eco/devices_general/vacuum/gauges.py index 8b44c57..86433dc 100644 --- a/eco/devices_general/vacuum/gauges.py +++ b/eco/devices_general/vacuum/gauges.py @@ -35,8 +35,12 @@ class VacuumGauge(Assembly): self._append( DetectorPvData, f"{pvbase}:PRESSURE", has_unit=True, name="pressure" ) - # controller status text, e.g. "MEASURE", "SENSOR OFF", "UNDER RANGE" - self._append(DetectorPvString, f"{pvbase}:STATUS", name="status") + # controller status text, e.g. "MEASURE", "SENSOR OFF", "UNDER RANGE". + # Named `status_text`, not `status` -- every Assembly already has a + # `.status()` method (the generic hierarchical status table), which + # a child actually named "status" would shadow with this plain PV + # string instead. + self._append(DetectorPvString, f"{pvbase}:STATUS", name="status_text") # --- gauge on/off (cold cathodes can be switched) ---------------- self._append( AdjustablePvEnum, f"{pvbase}:ONOFF", name="on", is_setting=True @@ -58,5 +62,12 @@ class VacuumGauge(Assembly): ) # controller unit name (e.g. TPG gauge controller) def get_current_value(self, *args, **kwargs): - """Read like a detector: return the pressure.""" + """Read like a detector: return the pressure, or ``None`` if the + gauge's emission is off (a pressure reading would be stale/ + meaningless in that state, per :attr:`on_readback`).""" + try: + if self.on_readback.get_current_value().name != "ON": + return None + except Exception: + pass return self.pressure.get_current_value(*args, **kwargs) diff --git a/eco/devices_general/vacuum/prepump.py b/eco/devices_general/vacuum/prepump.py index 9494dd2..7c6878d 100644 --- a/eco/devices_general/vacuum/prepump.py +++ b/eco/devices_general/vacuum/prepump.py @@ -35,10 +35,17 @@ is just the dumb valve/gauge group for one channel. import time from eco import Assembly +from eco.elements.detector import DetectorVirtual from .gauges import VacuumGauge from .valves import Valve, PrePump, ValveState +#: Default pressure thresholds [mbar], shared by PrepumpSystem and by any +#: PrepumpLine that doesn't override them: at/below `P_TARGET` a channel +#: counts as "pumped", at/above `P_VENT_TARGET` as "vented". +P_TARGET = 0.5 +P_VENT_TARGET = 1000.0 + class PrepumpLine(Assembly): """One prepump/venting channel: pump valve ``valve_prevac`` (P), vent @@ -47,27 +54,107 @@ class PrepumpLine(Assembly): Any of ``gauge`` / ``valve_prevac`` / ``valve_vent`` left ``None`` is simply not built, so a not-yet-cabled channel still works for the parts that exist. + + ``prepump_system``, if given, is the owning :class:`PrepumpSystem` -- + channels built through :func:`make_prepump_system`/``PrepumpSystem`` + get it wired up automatically, so it normally doesn't need to be passed + explicitly. It's what lets :meth:`pump_down`/:meth:`vent` be called + directly on the channel (``line1_usd.pump_down()``) instead of only via + the system's string-keyed form (``prepump.pump_down('line1_usd')``, + still there and equivalent -- the cross-channel interlock logic lives on + the system either way, since it must coordinate all channels). """ - def __init__(self, name=None, gauge=None, valve_prevac=None, valve_vent=None): + def __init__(self, name=None, gauge=None, valve_prevac=None, valve_vent=None, + prepump_system=None, p_target=None, p_vent_target=None): super().__init__(name=name) + self.prepump_system = prepump_system + self._p_target = p_target + self._p_vent_target = p_vent_target if gauge is not None: - self._append(VacuumGauge, gauge, name="gauge", is_status=True) + self._append(VacuumGauge, gauge, name="gauge", + is_display=True, is_status=True) if valve_prevac is not None: - self._append(Valve, valve_prevac, name="valve_prevac", is_setting=True) + self._append(Valve, valve_prevac, name="valve_prevac", + is_display=True, is_setting=True) if valve_vent is not None: - self._append(Valve, valve_vent, name="valve_vent", is_setting=True) + self._append(Valve, valve_vent, name="valve_vent", + is_display=True, is_setting=True) + # this channel's state, computed from the components above -- see + # `state()`. A plain Detector child so it shows up as one more row in + # the display/status table alongside what it is derived from. + self._append(DetectorVirtual, [], self.state, name="state", + is_display=True, is_status=True) + + # ---- thresholds ---------------------------------------------------- + # Resolved per channel: an explicit per-line value wins, else the owning + # system's, else the module default. Per-line overrides are meaningful -- + # channels have different gauges (a Pirani tops out well below ambient, + # so "vented" isn't the same number everywhere) and different chambers. + @property + def p_target(self): + if self._p_target is not None: + return self._p_target + return getattr(self.prepump_system, "p_target", P_TARGET) + + @property + def p_vent_target(self): + if self._p_vent_target is not None: + return self._p_vent_target + return getattr(self.prepump_system, "p_vent_target", P_VENT_TARGET) def pressure(self): - """This channel's gauge pressure, or None if no gauge/reading.""" + """This channel's gauge pressure, or None if no gauge/reading/the + gauge is off (see VacuumGauge.get_current_value).""" gauge = getattr(self, "gauge", None) if gauge is None: return None try: - return gauge.pressure.get_current_value() + return gauge.get_current_value() except Exception: return None + def is_pumped(self): + """True if this channel's own gauge is at/below its `p_target`.""" + p = self.pressure() + return p is not None and p <= self.p_target + + def is_vented(self): + """True if this channel's own gauge is at/above its `p_vent_target`.""" + p = self.pressure() + return p is not None and p >= self.p_vent_target + + def state(self): + """Classify this channel from its *own* valve positions and gauge + (nothing from the rest of the system except the pressure thresholds, + which are per-channel overridable -- notably NOT the common ``Gp``): + + * ``"pumped"`` -- pump valve open, gauge at/below ``p_target`` + (its normal connected, pumped-down steady state) + * ``"pumping"`` -- pump valve open, gauge still above ``p_target`` + (a pump down is in progress) + * ``"venting"`` -- vent valve open (a vent is in progress, or it + was simply left open) + * ``"vented"`` -- both valves closed, gauge at/above + ``p_vent_target`` (sealed off at atmosphere) + * ``"isolated"`` -- both valves closed, gauge below + ``p_vent_target`` (sealed off, still holding some vacuum) + * ``"unknown"`` -- a valve/gauge reading isn't available, or both + valves are open at once (should never happen) + """ + try: + prevac_open = self.valve_prevac.get_current_value() == ValveState.OPEN + vent_open = self.valve_vent.get_current_value() == ValveState.OPEN + except Exception: + return "unknown" + if prevac_open and vent_open: + return "unknown" + if vent_open: + return "venting" + if prevac_open: + return "pumped" if self.is_pumped() else "pumping" + return "vented" if self.is_vented() else "isolated" + def isolate(self): """Close this channel off from both the pump and vent line (safe state).""" if getattr(self, "valve_prevac", None) is not None: @@ -75,6 +162,30 @@ class PrepumpLine(Assembly): if getattr(self, "valve_vent", None) is not None: self.valve_vent.close() + def _require_prepump_system(self, method_name): + if self.prepump_system is None: + raise RuntimeError( + f"'{self.name}' has no prepump_system set, so {method_name}() " + f"can't run the cross-channel interlock -- call it on the " + f"system instead, e.g. prepump.{method_name}('{self.name}')." + ) + return self.prepump_system + + def pump_down(self, timeout=300.0, poll=1.0): + """Pump this channel down -- convenience wrapper for + ``self.prepump_system.pump_down(self, ...)``, see there for what it + actually does (isolating the other channels etc.).""" + return self._require_prepump_system("pump_down").pump_down( + self, timeout=timeout, poll=poll + ) + + def vent(self, timeout=300.0, poll=1.0): + """Vent this channel -- convenience wrapper for + ``self.prepump_system.vent(self, ...)``.""" + return self._require_prepump_system("vent").vent( + self, timeout=timeout, poll=poll + ) + def get_current_value(self, *args, **kwargs): """A compact {valve role: valve state, 'pressure': p} snapshot.""" out = {} @@ -115,7 +226,7 @@ class PrepumpSystem(Assembly): """ def __init__(self, name=None, gp=None, roots_pump=None, lines=None, - p_target=0.5, p_vent_target=1000.0, vent_line_name="GN2"): + p_target=P_TARGET, p_vent_target=P_VENT_TARGET, vent_line_name="GN2"): super().__init__(name=name) self.p_target = p_target self.p_vent_target = p_vent_target @@ -133,8 +244,13 @@ class PrepumpSystem(Assembly): if isinstance(line, dict): # build a PrepumpLine from a plain kwargs dict (config form); # the dict's own "name" (if any) is overridden by the key. - line = PrepumpLine(**{**line, "name": lname}) - self._append(line, name=lname, is_status=True) + line = PrepumpLine(**{**line, "name": lname, "prepump_system": self}) + else: + # a ready-made PrepumpLine passed directly -- wire it up too, + # so line1_usd.pump_down() works regardless of which form + # built it. + line.prepump_system = self + self._append(line, name=lname, is_display=True, is_status=True) self._line_names.append(lname) # ---- helpers ------------------------------------------------------- @@ -151,52 +267,29 @@ class PrepumpSystem(Assembly): return got def gp_pressure(self): - """Common pump-line pressure (Gp), or None.""" + """Common pump-line pressure (Gp), or None (see + VacuumGauge.get_current_value, incl. the gauge-off case).""" gp = getattr(self, "gp", None) if gp is None: return None try: - return gp.pressure.get_current_value() + return gp.get_current_value() except Exception: return None def _is_pumped(self, pressure): + """Only used for the *common* line's ``Gp`` now -- a channel's own + gauge is judged by `PrepumpLine.is_pumped`/`is_vented` against that + channel's (possibly overridden) thresholds.""" return pressure is not None and pressure <= self.p_target - def _is_vented(self, pressure): - return pressure is not None and pressure >= self.p_vent_target - def line_state(self, line): - """Classify one channel's current state from its own valve - positions and gauge reading (not the common ``Gp``): - - * ``"pumped"`` -- pump valve open, gauge at/below ``p_target`` - (its normal connected, pumped-down steady state) - * ``"pumping"`` -- pump valve open, gauge still above ``p_target`` - (a pump down is in progress) - * ``"venting"`` -- vent valve open (a vent is in progress, or it - was simply left open) - * ``"vented"`` -- both valves closed, gauge at/above - ``p_vent_target`` (sealed off at atmosphere) - * ``"isolated"`` -- both valves closed, gauge below - ``p_vent_target`` (sealed off, still holding some vacuum) - * ``"unknown"`` -- a valve/gauge reading isn't available, or both - valves are open at once (should never happen) - """ - line = self._get_line(line) - try: - prevac_open = line.valve_prevac.get_current_value() == ValveState.OPEN - vent_open = line.valve_vent.get_current_value() == ValveState.OPEN - except Exception: - return "unknown" - if prevac_open and vent_open: - return "unknown" - if vent_open: - return "venting" - p = line.pressure() - if prevac_open: - return "pumped" if self._is_pumped(p) else "pumping" - return "vented" if self._is_vented(p) else "isolated" + """One channel's current state -- thin delegate to + :meth:`PrepumpLine.state`, which is where the classification lives + (it needs nothing from the system beyond the pressure thresholds the + channel already inherits). Kept because it accepts the string form, + e.g. ``prepump.line_state('line1_usd')``.""" + return self._get_line(line).state() # ---- procedures ------------------------------------------------------ def pump_down(self, line, timeout=700.0, poll=1.0): @@ -236,7 +329,9 @@ class PrepumpSystem(Assembly): print(f"[prepump] '{other.name}' was not pumped/connected before -- leaving it as is") t0 = time.time() - while not (self._is_pumped(self.gp_pressure()) and self._is_pumped(line.pressure())): + # Gp against the system threshold, the channel's gauge against its + # own (a channel may override it, see PrepumpLine.p_target). + while not (self._is_pumped(self.gp_pressure()) and line.is_pumped()): if time.time() - t0 > timeout: self._activity = (f"pump_down('{line.name}') FAILED after {timeout:.0f}s " f"(Gp={_fmt_pressure(self.gp_pressure())}, G={_fmt_pressure(line.pressure())})") @@ -284,7 +379,7 @@ class PrepumpSystem(Assembly): line.valve_vent.open() t0 = time.time() - while not self._is_vented(line.pressure()): + while not line.is_vented(): if time.time() - t0 > timeout: self._activity = f"vent('{line.name}') FAILED after {timeout:.0f}s (G={_fmt_pressure(line.pressure())})" print(f"[prepump] '{line.name}' venting FAILED after {timeout}s (G={line.pressure()})") @@ -641,13 +736,16 @@ def make_prepump_system(config, name="prepump"): { "gp": "", # common prevac-line gauge "roots_pump": "", - "p_target": 1e-3, # optional, mbar (default 1e-3) - "p_vent_target": 500.0, # optional, mbar (default 500.0) + "p_target": 0.5, # optional, mbar (default P_TARGET) + "p_vent_target": 1000.0, # optional, mbar (default P_VENT_TARGET) "lines": { "": { "gauge": "", # this channel's gauge "valve_prevac": "

", # -> prevac/roots line "valve_vent": "", # -> GN2 vent line + # optional per-channel threshold overrides; omitted = inherit + # the system's (see PrepumpLine.p_target) + # "p_target": 0.5, "p_vent_target": 1000.0, }, ... }, @@ -665,8 +763,8 @@ def make_prepump_system(config, name="prepump"): gp=cfg.get("gp"), roots_pump=cfg.get("roots_pump"), lines=cfg.get("lines", {}), - p_target=cfg.get("p_target", 1e-3), - p_vent_target=cfg.get("p_vent_target", 500.0), + p_target=cfg.get("p_target", P_TARGET), + p_vent_target=cfg.get("p_vent_target", P_VENT_TARGET), ) @@ -678,8 +776,8 @@ def make_prepump_system(config, name="prepump"): BERNINA_PREPUMP_CONFIG = { "gp": None, # common prevac-line gauge Gp base "roots_pump": None, # Roots pump base - "p_target": 1e-3, # "pumped" threshold [mbar] - "p_vent_target": 500.0, # "vented" threshold [mbar] + "p_target": P_TARGET, # "pumped" threshold [mbar] + "p_vent_target": P_VENT_TARGET, # "vented" threshold [mbar] "lines": { "line1": {"gauge": None, "valve_prevac": None, "valve_vent": None}, "line2": {"gauge": None, "valve_prevac": None, "valve_vent": None}, diff --git a/eco/devices_general/vacuum/valves.py b/eco/devices_general/vacuum/valves.py index 688d255..58f7872 100644 --- a/eco/devices_general/vacuum/valves.py +++ b/eco/devices_general/vacuum/valves.py @@ -21,7 +21,6 @@ Minimal use:: from enum import Enum from eco import Assembly -from eco.elements.adjustable import AdjustableGetSet from eco.elements.detector import DetectorVirtual from eco.epics_utils.adjustable import AdjustablePv, AdjustablePvEnum from eco.epics_utils.detector import DetectorPvData, DetectorPvEnum, DetectorPvString @@ -51,11 +50,19 @@ _STATE_TO_COMMAND = {state: command for command, state in _COMMAND_TO_STATE.item class Valve(Assembly): """A pneumatic vacuum valve. - The command is :attr:`request` (an enum, ``open``/``close``); the true state - comes from the two PLC readbacks :attr:`open_readback` and - :attr:`closed_readback`. :meth:`open` / :meth:`close` are convenience - wrappers, and :meth:`get_current_value` collapses the two readbacks into a - single human-readable state. + Exactly two status children, since that's all there is to show: the + write channel :attr:`request` (an enum, ``open``/``close``) and the true + state :attr:`readback` (collapsed from the two raw PLC limit switches, + which stay internal -- there's nothing to gain from showing both a raw + open switch and a raw closed switch alongside the state they already + combine into). :meth:`get_current_value`/:meth:`set_target_value`/ + :attr:`enum_strs` on the Valve itself are plain delegates to those two, + so the valve is directly usable as an Adjustable/Detector without + reaching into either child; :meth:`open`/:meth:`close` are further + convenience wrappers around :meth:`set_target_value`. :attr:`is_open` + and :attr:`error_message` are still there for programmatic use (a + beamline's transmission logic, PLC fault text) but out of the default + status view -- they're both derived from/duplicate of `readback`. """ def __init__(self, pvbase, name=None): @@ -63,26 +70,39 @@ class Valve(Assembly): self.pvbase = pvbase # open/close command sent to the PLC (enum: "open"/"close") self._append( - AdjustablePvEnum, f"{pvbase}:REQUEST", name="_request", is_setting=True + AdjustablePvEnum, f"{pvbase}:REQUEST", name="request", is_setting=True ) - # PLC limit-switch readbacks (enum ON/OFF); both ON/OFF => moving/fault - self._append(DetectorPvEnum, f"{pvbase}:PLC_OPEN", name="_open_readback") - self._append(DetectorPvEnum, f"{pvbase}:PLC_CLOSE", name="_closed_readback") - + # PLC limit-switch readbacks (enum ON/OFF); both ON/OFF => moving/fault. + # Internal only -- get_current_value() below collapses them into the + # single `readback` child, so showing these two raw switches as well + # would just be the same information twice. + # + # NOTE `is_display=False` is what actually keeps a child out of the + # shell table / `repr(valve)`: `__repr__` -> `get_display_str()` reads + # the "display" status_collection selection, which `_append` fills + # from `is_display` (`is_status` feeds `get_status()`/the status + # server instead). Both are set here -- these are internal plumbing + # for either purpose. + self._append(DetectorPvEnum, f"{pvbase}:PLC_OPEN", name="_open_readback", + is_display=False, is_status=False) + self._append(DetectorPvEnum, f"{pvbase}:PLC_CLOSE", name="_closed_readback", + is_display=False, is_status=False) + # the valve's true state, collapsed from the two switches above -- + # literally `self.get_current_value` re-exposed as a child Detector + self._append(DetectorVirtual, [], self.get_current_value, name="readback") + # human-readable PLC status/fault text for this valve (diagnostic, + # not part of the default display) self._append( - AdjustableGetSet, self.get_current_value, self._request.set_target_value, - name="status", - ) - # human-readable PLC status/fault text for this valve - self._append( - DetectorPvString, f"{pvbase}:PLC_ER_MESSAGE", name="error_message" + DetectorPvString, f"{pvbase}:PLC_ER_MESSAGE", name="error_message", + is_display=False, is_status=False, ) # boolean "beam can pass" view of the state, so a beamline model's # transmission logic (Beamline.diagram / _read_open_state) can read # this valve the same way it reads any other blocking component. + # Pure duplicate of `readback` for display purposes, so hidden there. self._append( DetectorVirtual, [], lambda: self.get_current_value() == ValveState.OPEN, - name="is_open", is_setting=False, + name="is_open", is_setting=False, is_display=False, is_status=False, ) def get_current_value(self, *args, **kwargs): @@ -106,13 +126,13 @@ class Valve(Assembly): get_current_value()'s full collapsed-readback state space (MOVING/INCONSISTENT/UNDEFINED/UNKNOWN are synthesized read-only states, never legal write targets). Sourced from the underlying - command PV's own enum table (`_request`), translated via + command PV's own enum table (`request`), translated via `_COMMAND_TO_STATE` to ValveState's upper-case member names so widget pulldowns -- which pre-select by matching get_current_value()'s `.name` -- still highlight the right entry instead of falling back to `enum.Enum.__members__` (every ValveState member).""" out = [] - for s in self._request.enum_strs: + for s in self.request.enum_strs: state = _COMMAND_TO_STATE.get(s) out.append(state.name if state is not None else s) return tuple(out) @@ -128,7 +148,7 @@ class Valve(Assembly): value = ValveState[value] if isinstance(value, ValveState): value = _STATE_TO_COMMAND.get(value, value.value) - return self._request.set_target_value(value) + return self.request.set_target_value(value) def open(self): """Request the valve to open.""" @@ -144,28 +164,35 @@ class FastValve(Assembly): Unlike :class:`Valve`, a fast valve is a **status-only** device in the VCS: it slams shut automatically on a pressure spike, and its arming/reset lives - in the PLC / upstream optics panel rather than here. Only the two PLC - limit-switch readbacks are exposed; :meth:`get_current_value` collapses them - into a state string, same convention as :class:`Valve`. + in the PLC / upstream optics panel rather than here. Same convention as + :class:`Valve`'s readback side (no write channel here, obviously): the two + raw PLC limit switches stay internal, collapsed into one :attr:`readback` + status child by :meth:`get_current_value`; :attr:`is_open` is out of the + default status view too, same reasoning as `Valve.is_open`. """ def __init__(self, pvbase, name=None): super().__init__(name=name) self.pvbase = pvbase - # PLC limit-switch readbacks (enum ON/OFF) - self._append(DetectorPvEnum, f"{pvbase}:PLC_OPEN", name="open_readback") - self._append(DetectorPvEnum, f"{pvbase}:PLC_CLOSE", name="closed_readback") + # PLC limit-switch readbacks (enum ON/OFF) -- internal, see Valve + # (incl. why hiding needs is_display, not just is_status) + self._append(DetectorPvEnum, f"{pvbase}:PLC_OPEN", name="_open_readback", + is_display=False, is_status=False) + self._append(DetectorPvEnum, f"{pvbase}:PLC_CLOSE", name="_closed_readback", + is_display=False, is_status=False) + # the valve's true state, collapsed from the two switches above + self._append(DetectorVirtual, [], self.get_current_value, name="readback") # boolean "beam can pass" view (see Valve.is_open) self._append( DetectorVirtual, [], lambda: self.get_current_value() == ValveState.OPEN, - name="is_open", is_setting=False, + name="is_open", is_setting=False, is_display=False, is_status=False, ) def get_current_value(self, *args, **kwargs): """Collapse the open/closed PLC readbacks into a single state string.""" try: - is_open = self.open_readback.get_current_value().name == "ON" - is_closed = self.closed_readback.get_current_value().name == "ON" + is_open = self._open_readback.get_current_value().name == "ON" + is_closed = self._closed_readback.get_current_value().name == "ON" except Exception: return ValveState.UNKNOWN if is_open and not is_closed: diff --git a/eco/utilities/svg_interactor.py b/eco/utilities/svg_interactor.py index 588fd00..0edc55b 100644 --- a/eco/utilities/svg_interactor.py +++ b/eco/utilities/svg_interactor.py @@ -1,6 +1,8 @@ import os import json +import queue import threading +import traceback from dash import Dash, html, dcc from dash.dependencies import Input, Output from flask import Response @@ -117,6 +119,62 @@ def _in_notebook(ip): return ip.__class__.__name__ == "ZMQInteractiveShell" +# -------------------------------------------------------------------------- +# Clicked-command execution +# -------------------------------------------------------------------------- +# A command clicked in a panel can run for a long time (e.g. clicking "pump" +# starts a `PrepumpSystem.pump_down()` that polls for minutes). Running it +# inline in the HTTP request that delivered the click would hold that request +# open for its whole duration -- so it is handed to a dedicated background +# worker instead and the request returns immediately. +# +# ONE worker, fed by a queue, deliberately: clicked commands then serialise +# against each other rather than running concurrently, which matters because +# they drive shared hardware (two vacuum macros interleaving valve writes on +# the same shared pump/vent line would be a real hazard, not just untidy). +_command_queue = None +_command_worker = None +_command_worker_lock = threading.Lock() + + +def _command_worker_loop(): + while True: + ip_instance, command_str = _command_queue.get() + try: + # pyepics binds its channel-access context per *thread*; a thread + # that never attaches to the process' initial context sees no + # connections at all (reads return None / hang), so a macro run + # here would silently misbehave without this. + try: + import epics + + epics.ca.use_initial_context() + except Exception: + pass + print(f"\nExecuting from SVG: {command_str}") + ip_instance.run_cell(command_str) + except Exception: + traceback.print_exc() + finally: + _command_queue.task_done() + + +def _dispatch_command(ip_instance, command_str): + """Queue `command_str` to run on the shared background worker (started + lazily on first use, and restarted if it ever died), and return at once.""" + global _command_queue, _command_worker + + with _command_worker_lock: + if _command_queue is None: + _command_queue = queue.Queue() + if _command_worker is None or not _command_worker.is_alive(): + _command_worker = threading.Thread( + target=_command_worker_loop, daemon=True, name="eco-svg-commands" + ) + _command_worker.start() + _command_queue.put((ip_instance, command_str)) + + def _run_dash_server(svg_path, ip_instance, namespace_prefix=None, exclude_group_ids=None, refresh=None, refresh_interval_ms=2000, port_holder=None): """Launches a local webserver hosting the interactive Inkscape SVG. @@ -192,6 +250,17 @@ def _run_dash_server(svg_path, ip_instance, namespace_prefix=None, exclude_group {%title%} {%favicon%} {%css%} + {%app_entry%} @@ -203,30 +272,38 @@ def _run_dash_server(svg_path, ip_instance, namespace_prefix=None, exclude_group @@ -287,17 +382,26 @@ def _run_dash_server(svg_path, ip_instance, namespace_prefix=None, exclude_group ) app.layout = html.Div([ - # 2. Changed from html.Embed to html.ObjectEl, served from a same-origin route + # 2. Changed from html.Embed to html.ObjectEl, served from a same-origin route. + # width/height 100% (of the now-reset, zero-margin body -- see the + #