prepump update

This commit is contained in:
lemke_h committed 2026-08-27 14:14:42 +02:00
1 parent acf4b7ce98
commit cf9d7e88b4
8 files changed
+958 -473

No files matched your search

+26 -31
View File
@@ -220,48 +220,43 @@ namespace.mark_beamline(
# Consolidated prepump/venting system (see eco.devices_general.vacuum.prepump
# for the model + spec this implements). One structured config dict holds
# every line's valve/gauge/turbo PV names, so the whole system can be edited
# here as a single literal. All PVs below are still None placeholders -- fill
# them in once known; a line with all-None PVs still builds (just empty).
# Line *kinds* are a guess (the source spec's "usage scenarios for permanent
# lines 1-2" was truncated) -- adjust once confirmed. Lazy, so nothing here
# touches EPICS until `prepump` is accessed.
# every channel's valve/gauge PV names, so the whole system can be edited
# here as a single literal. A channel with all-None PVs still builds (just
# empty). Lazy, so nothing here touches EPICS until `prepump` is accessed.
# Turbo pumps are not modelled here -- they're served by the prepump system
# but not part of it (see the module docstring).
_prepump_config = {
"gp": "SARES21-VMCP142-620", # common prevac-line gauge Gp base
"roots_pump": "SARES21-VPFO140-750", # Roots pump base
"p_target": 1e-3, # "pumped" threshold [mbar]
"p_vent_target": 500.0, # "vented" threshold [mbar]
"lines": {
# permanent dual-access chambers (guess: prepump_access) -------------
"line1_usd": {
"kind": "turbo",
"gauge": "SARES21-VMFR140-510", # G1 gauge base
"turbo": "SARES21-VPTM140-700", # turbo pump base
"valve_prevac": "SARES21-VVPP140-300", # P2 chamber roughing valve
"valve_vent": "SARES21-VVPP142-340", # V2 chamber vent valve
"valve_prevac": "SARES21-VVPP140-300", # P1 roughing valve
"valve_vent": "SARES21-VVPP142-340", # V1 vent valve
},
"line2_lic": {
"kind": "turbo",
"gauge": "SARES21-VMCP141-531", # G1 gauge base
"turbo": "SARES21-VPTM141-710", # turbo pump base
"valve_prevac": "SARES21-VVPP141-320", # P2 chamber roughing valve
"valve_vent": "SARES21-VVPP142-370", # V2 chamber vent valve
"gauge": "SARES21-VMCP141-531", # G2 gauge base
"valve_prevac": "SARES21-VVPP141-320", # P2 roughing valve
"valve_vent": "SARES21-VVPP142-370", # V2 vent valve
},
# line 3 : valve_vent : "143-350", valve_prevac 142-330""
# line 4 : valve_vent : "142-340", valve_prevac
# "line2": {
# "kind": "prepump_access",
# "gauge": None, "turbo": None,
# "valve_prevac": None, "valve_vent": None,
# "valve_turbo_prevac": None, "valve_turbo_access": None,
# channels 3-4: valve PVs noted from commissioning, gauges not yet
# assigned -- fill in the TODOs below, then uncomment.
"line3": {
"gauge": "SARES21-VMCP142-570", # TODO: G3 gauge base
"valve_prevac": "SARES21-VVPG142-330", # TODO: was noted as "...142-330"
"valve_vent": "SARES21-VVPG143-350", # TODO: was noted as "...143-350"
},
# "line4": {
# "gauge": None, # TODO: G4 gauge base
# "valve_prevac": None, # TODO: not yet noted
# "valve_vent": None, # TODO: was noted as "...142-340" -- looked
# # identical to line1_usd's, double check
# },
# # classic turbo prepump lines (guess: turbo) -------------------------
# "line3": {"kind": "turbo", "gauge": None, "turbo": None,
# "valve_prevac": None, "valve_vent": None},
# "line4": {"kind": "turbo", "gauge": None, "turbo": None,
# "valve_prevac": None, "valve_vent": None},
# # beam-transport pipe, pre-vacuum only (guess: transport) -----------
# "line5": {"kind": "transport", "gauge": None,
# "valve_prevac": None, "valve_vent": None},
# two more optional slots, not yet cabled:
# "line5": {"gauge": None, "valve_prevac": None, "valve_vent": None},
# "line6": {"gauge": None, "valve_prevac": None, "valve_vent": None},
},
}
namespace.append_obj(
+54
View File
@@ -305,6 +305,12 @@ class CamserverConfig(Assembly):
class CameraBasler(Assembly):
# widget() (and anything driving it, e.g. the desktop app's namespace
# launcher) opens the live cam_server viewer instead of the generic
# property grid -- mirrors eco.devices_general.cameras_ptz.AxisPTZ. See
# Assembly._default_widget/viewer() below.
_default_widget = "viewer"
def __init__(
self,
pvname,
@@ -622,6 +628,30 @@ class CameraBasler(Assembly):
f'caqtdm -macro "NAME={self.pvname},CAMNAME={self.pvname}" /sf/controls/config/qt/Camera/CameraExpert.ui'
)
def viewer(
self, pipeline_url=None, rate_hz=10.0, theme=None, auto_start=True
):
"""Open the live cam_server "screen panel" viewer for this camera's
own default processing pipeline -- the pipeline name is resolved
automatically from self.pvname (no need to know or guess a
pipeline/instance name), mirroring pshell's own screen panel (see
eco.widgets.camserver_stream_qt.resolve_camera_pipeline for the
exact "{camera}_sp" naming convention and auto-create-if-missing
behavior this reuses). The window's "Camera Settings" button opens
widget(normal=True) (the normal property-grid display) -- mirrors
eco.devices_general.cameras_ptz.AxisPTZ.viewer()."""
from ..widgets.camserver_stream_qt import make_camserver_stream_qt
return make_camserver_stream_qt(
self.pvname,
kind="camera_pipeline",
pipeline_url=pipeline_url,
rate_hz=rate_hz,
theme=theme,
auto_start=auto_start,
cam=self,
)
# NB: please note this should be moved to microscopes which are using cameras plus zooms,
class QioptiqMicroscope(CameraBasler):
@@ -634,6 +664,12 @@ class QioptiqMicroscope(CameraBasler):
class CameraPCO(Assembly):
# widget() (and anything driving it, e.g. the desktop app's namespace
# launcher) opens the live cam_server viewer instead of the generic
# property grid -- mirrors CameraBasler/eco.devices_general.cameras_ptz.
# AxisPTZ. See Assembly._default_widget/viewer() below.
_default_widget = "viewer"
def __init__(self, pvname, camserver_alias=None, name=None):
super().__init__(name=name)
self.pvname = pvname
@@ -723,6 +759,24 @@ class CameraPCO(Assembly):
f'caqtdm -macro "NAME={self.pvname},CAMNAME={self.pvname}" /sf/controls/config/qt/Camera/CameraExpert.ui'
)
def viewer(
self, pipeline_url=None, rate_hz=10.0, theme=None, auto_start=True
):
"""Open the live cam_server "screen panel" viewer for this camera's
own default processing pipeline -- see CameraBasler.viewer(), which
this mirrors."""
from ..widgets.camserver_stream_qt import make_camserver_stream_qt
return make_camserver_stream_qt(
self.pvname,
kind="camera_pipeline",
pipeline_url=pipeline_url,
rate_hz=rate_hz,
theme=theme,
auto_start=auto_start,
cam=self,
)
# NB: please note this should be moved to microscopes which are using cameras plus zooms,
class FeturaMicroscope(CameraBasler):
+243 -421
View File
@@ -1,43 +1,35 @@
"""Bernina consolidated prepump / venting system as an eco object.
Models the new Bernina prepump system (spec: "Prepump system on turbo prepump
Models the Bernina prepump system (spec: "Prepump system on turbo prepump
line"): a single high-performance **Roots pump** feeds a common **pump line**
(pressure gauge ``Gp``); a separate **GN2 vent line** (low overpressure) allows
controlled venting. Up to five **prepump/venting lines** branch off, each with
(pressure gauge ``Gp``); a separate **GN2 vent line** (low overpressure)
allows controlled venting. Any number of **prepump/venting channels** branch
off, each with exactly
* a **pump valve** ``P`` (line -> common pump line),
* a **vent valve** ``V`` (line -> vent line),
* its own gauge ``G``,
* and usually a **turbo pump** it backs (the turbo is *served by* the prepump
system, not part of it).
* a **pump valve** ``valve_prevac`` (P: channel -> common pump line),
* a **vent valve** ``valve_vent`` (V: channel -> vent line),
* its own gauge ``gauge`` (G).
Because ``Gp`` rises during a pumpdown, the *other* lines must be isolated while
one line is pumped, so they don't pump against too high a pressure. That
cross-line interlock is the job of :class:`PrepumpSystem`; the per-line valve
choreography is :class:`PrepumpLine`.
(A channel's turbo pump, if it has one, is served by the prepump system but
is not part of it -- it is exchangeable and plays no role in the valve
choreography, see the spec: "does not belong to the prepump system" -- so it
is deliberately not modelled here at all.)
Line types (one per table in the spec)
--------------------------------------
``turbo`` classic turbo prepump line: valves ``pump`` (P), ``vent`` (V).
``transport`` same valves, but a beam-transport pipe with no turbo.
``vent_access`` turbo vent-access variant (spec table 3); ``pump`` + ``vent``.
``prepump_access`` dual-access line (spec table 2) for fast sample exchange:
the turbo keeps spinning in its own isolated section while
the chamber is vented. Valves ``turbo_pump`` (P1),
``turbo_access`` (T), ``chamber_pump`` (P2),
``chamber_vent`` (V2).
There is only this one channel scheme (the spec's dual-access "prepump
access" variant for fast sample exchange is a separate, higher-level
procedure and not modelled here).
You supply the real EPICS PV base names per component (see
:func:`make_bernina_prepump_system`, whose five lines are placeholders to fill
in). The pressure thresholds default to a single target (``p_target``, mbar):
a gauge is "pumped" when it reads at/below it, "high" otherwise -- matching the
spec's ``1e-3`` / ``high`` columns.
Because ``Gp`` rises while a channel is being pumped down, every *other*
channel's pump valve must be closed meanwhile, so it doesn't get pumped
against too high a pressure -- that cross-channel interlock plus the actual
pump-down/vent choreography is :class:`PrepumpSystem`; :class:`PrepumpLine`
is just the dumb valve/gauge group for one channel.
.. note::
The final spec section ("usage scenarios for permanent lines 1-2") is
truncated in the source document. The five lines / kinds in
:func:`make_bernina_prepump_system` are therefore a **best guess** and marked
as such -- correct them once the intended assignment is known.
The GN2 vent line's flow meter ``Fv`` (limits vent flow/overpressure) does
not exist as a controllable/readable device yet. Nothing here uses it --
see the commented-out notes in :func:`build_prepump_svg` and
:meth:`PrepumpSystem.vent` for where it would plug in once it does.
"""
import time
@@ -45,223 +37,61 @@ import time
from eco import Assembly
from .gauges import VacuumGauge
from .pumps import TurboPump
from .valves import Valve, PrePump
# --------------------------------------------------------------------------
# Verbatim reference of the spec's state tables (for audit against the doc).
# "high"/"1e-3" are the gauge *conditions* that identify a state; open/close are
# the *valve commands*. "others" = every OTHER line's pump / vent valves (the
# spec's P2-Pn / V2-Vn columns), handled by PrepumpSystem, not the line itself.
# --------------------------------------------------------------------------
#: spec table 1 -- "Actions for section 1" (classic turbo prepump line)
_DOC_TABLE_TURBO = {
# state Gp G1 P1 V1 P2-Pn V2-Vn
"pump_down": ("high", "high", "open", "close", "close", "close"),
"pump_down_success": ("1e-3", "1e-3", "open", "close", "open", "close"),
"pump_down_failed_start": ("high", "high", "close","close", "close", "close"),
"pump_down_failed_end": ("1e-3", "high", "close","close", "open", "close"),
"venting": ("1e-3", "high", "close","open", "open", "close"),
}
#: spec table 2 -- "Actions for section with prepump access" (dual line)
_DOC_TABLE_PREPUMP_ACCESS = {
# state Gp G1 P1 T P2 V2 P3-Pn V3-Vn
"pump_down": ("high", "high", "close","close", "open", "close", "close", "close"),
"pump_down_success": ("1e-3", "1e-3", "open", "open", "close","close", "open", "close"),
"pump_down_failed_start": ("high", "high", "close","close", "close","close", "close", "close"),
"pump_down_failed_end": ("1e-3", "high", "close","close", "close","close", "open", "close"),
"venting": ("1e-3", "high", "close","close", "close","open", "open", "close"),
}
#: spec table 3 -- "Vent access to turbo pumps" (V column is greyed = optional)
_DOC_TABLE_VENT_ACCESS = {
# state Gp G1 P1 V(grey) P2-Pn V2-Vn
"pump_down": ("high", "high", "open", "open", "close", "close"),
"pump_down_success": ("1e-3", "1e-3", "open", "open", "open", "close"),
"pump_down_failed_start": ("high", "high", "close","open", "close", "close"),
"pump_down_failed_end": ("1e-3", "high", "close","open", "open", "close"),
"venting": ("1e-3", "high", "close","open", "open", "close"),
}
# --------------------------------------------------------------------------
# Operational state machine, per line kind: state -> {valve role: command}.
# Derived from the tables above, keeping only *this line's own* valves (the
# cross-line "others" columns are applied by PrepumpSystem via isolate/restore).
# Four operational states are enough to run everything:
# isolated -- all this line's valves closed (safe; the "failed_start" row)
# pump_down -- actively roughing this line
# connected -- nominal steady state, line on the pump line ("success" row)
# venting -- venting this line through the vent line
# --------------------------------------------------------------------------
#
# Every line has the two common valves ``valve_prevac`` (P: line -> common
# prevac/roots line) and ``valve_vent`` (V: line -> GN2 vent line). A
# ``prepump_access`` line adds two turbo-side valves: ``valve_turbo_prevac``
# (P1: backs the independently-spinning turbo) and ``valve_turbo_access``
# (T: isolates the turbo from the chamber). For that kind, ``valve_prevac`` /
# ``valve_vent`` are the *chamber's* direct roughing/vent valves (spec P2/V2).
# --------------------------------------------------------------------------
STATE_TABLES = {
"turbo": {
"isolated": {"valve_prevac": "close", "valve_vent": "close"},
"pump_down": {"valve_prevac": "open", "valve_vent": "close"},
"connected": {"valve_prevac": "open", "valve_vent": "close"},
"venting": {"valve_prevac": "close", "valve_vent": "open"},
},
"transport": { # no turbo, otherwise identical to a classic turbo line
"isolated": {"valve_prevac": "close", "valve_vent": "close"},
"pump_down": {"valve_prevac": "open", "valve_vent": "close"},
"connected": {"valve_prevac": "open", "valve_vent": "close"},
"venting": {"valve_prevac": "close", "valve_vent": "open"},
},
"vent_access": { # spec table 3; the vent valve is the turbo's own (optional)
"isolated": {"valve_prevac": "close", "valve_vent": "open"},
"pump_down": {"valve_prevac": "open", "valve_vent": "open"},
"connected": {"valve_prevac": "open", "valve_vent": "open"},
"venting": {"valve_prevac": "close", "valve_vent": "open"},
},
"prepump_access": { # spec table 2 (P1=turbo_prevac, T=turbo_access, P2=prevac, V2=vent)
"isolated": {"valve_turbo_prevac": "close", "valve_turbo_access": "close", "valve_prevac": "close", "valve_vent": "close"},
"pump_down": {"valve_turbo_prevac": "close", "valve_turbo_access": "close", "valve_prevac": "open", "valve_vent": "close"},
"connected": {"valve_turbo_prevac": "open", "valve_turbo_access": "open", "valve_prevac": "close", "valve_vent": "close"},
"venting": {"valve_turbo_prevac": "close", "valve_turbo_access": "close", "valve_prevac": "close", "valve_vent": "open"},
},
}
#: valve roles expected per line kind (also the order they are drawn/listed).
ROLE_SETS = {
"turbo": ["valve_prevac", "valve_vent"],
"transport": ["valve_prevac", "valve_vent"],
"vent_access": ["valve_prevac", "valve_vent"],
"prepump_access": ["valve_prevac", "valve_vent", "valve_turbo_prevac", "valve_turbo_access"],
}
#: which roles connect the line to the common prevac/roots line vs the vent
#: line -- used by the schematic and by isolate() reasoning.
_PUMP_SIDE_ROLES = {"valve_prevac", "valve_turbo_prevac"}
_VENT_SIDE_ROLES = {"valve_vent"}
class PrepumpLine(Assembly):
"""One prepump/venting line (one of the system's five "exits").
"""One prepump/venting channel: pump valve ``valve_prevac`` (P), vent
valve ``valve_vent`` (V), gauge ``gauge`` (G) -- see module docstring.
Configure with the EPICS PV base names of its components; any left ``None``
are simply not built, so a partially-cabled line still works for the parts
that exist. Every line has the two common valves:
* ``valve_prevac=`` -- P, connects the line to the common prevac/roots line
* ``valve_vent=`` -- V, connects the line to the GN2 vent line
and, depending on ``kind`` (see :data:`ROLE_SETS`), a ``prepump_access``
line additionally has the turbo-side valves:
* ``valve_turbo_prevac=`` -- P1, backs the (independently spinning) turbo
* ``valve_turbo_access=`` -- T, isolates the turbo from the chamber
plus ``gauge=`` (this line's ``G``) and, optionally, ``turbo=`` (the turbo
pump this line backs/serves).
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.
"""
def __init__(self, name=None, kind="turbo", gauge=None, turbo=None,
valve_prevac=None, valve_vent=None,
valve_turbo_prevac=None, valve_turbo_access=None):
def __init__(self, name=None, gauge=None, valve_prevac=None, valve_vent=None):
super().__init__(name=name)
if kind not in STATE_TABLES:
raise ValueError(
f"unknown prepump line kind {kind!r}; expected one of "
f"{sorted(STATE_TABLES)}"
)
self.kind = kind
self._roles = ROLE_SETS[kind]
self._valve_names = []
valve_pvs = {
"valve_prevac": valve_prevac,
"valve_vent": valve_vent,
"valve_turbo_prevac": valve_turbo_prevac,
"valve_turbo_access": valve_turbo_access,
}
# gauge for this line's own pressure (G1..Gn)
if gauge is not None:
self._append(VacuumGauge, gauge, name="gauge", is_status=True)
# the valves that this kind of line has
for role in self._roles:
pv = valve_pvs.get(role)
if pv is not None:
self._append(Valve, pv, name=role, is_setting=True)
self._valve_names.append(role)
# the turbo this line backs (served by, not part of, the prepump system)
if turbo is not None:
self._append(TurboPump, turbo, name="turbo", is_status=True)
# warn about valve args given but not used by this kind (typo guard)
extra = [r for r in ("valve_prevac", "valve_vent", "valve_turbo_prevac",
"valve_turbo_access")
if valve_pvs[r] is not None and r not in self._roles]
if extra:
print(f"[{name}] ignoring valve args not used by kind {kind!r}: {extra}")
if valve_prevac is not None:
self._append(Valve, valve_prevac, name="valve_prevac", is_setting=True)
if valve_vent is not None:
self._append(Valve, valve_vent, name="valve_vent", is_setting=True)
# ---- low-level valve choreography ---------------------------------
def _valve(self, role):
v = getattr(self, role, None)
if v is None:
raise RuntimeError(
f"prepump line '{self.name}': valve role '{role}' is not "
"configured (no PV given)."
)
return v
def set_state(self, state):
"""Drive this line's own valves to the named operational state
(``isolated`` / ``pump_down`` / ``connected`` / ``venting``). Missing
(unconfigured) valves are skipped with a warning."""
table = STATE_TABLES[self.kind]
if state not in table:
raise ValueError(f"unknown state {state!r}; expected {sorted(table)}")
for role, command in table[state].items():
valve = getattr(self, role, None)
if valve is None:
print(f"[{self.name}] state '{state}': skipping unconfigured valve '{role}'")
continue
(valve.open if command == "open" else valve.close)()
def isolate(self):
"""Close this line off from both pump and vent lines (safe state)."""
self.set_state("isolated")
def restore(self):
"""Return this line to its nominal connected steady state."""
self.set_state("connected")
# ---- readback ------------------------------------------------------
def pressure(self):
"""This line's gauge pressure, or None if no gauge/reading."""
g = getattr(self, "gauge", None)
if g is None:
"""This channel's gauge pressure, or None if no gauge/reading."""
gauge = getattr(self, "gauge", None)
if gauge is None:
return None
try:
return g.pressure.get_current_value()
return gauge.pressure.get_current_value()
except Exception:
return None
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:
self.valve_prevac.close()
if getattr(self, "valve_vent", None) is not None:
self.valve_vent.close()
def get_current_value(self, *args, **kwargs):
"""A compact {role: valve-state, 'pressure': p} snapshot."""
"""A compact {valve role: valve state, 'pressure': p} snapshot."""
out = {}
for role in self._valve_names:
try:
out[role] = self._valve(role).get_current_value()
except Exception:
out[role] = "?"
for role in ("valve_prevac", "valve_vent"):
valve = getattr(self, role, None)
out[role] = valve.get_current_value() if valve is not None else "?"
out["pressure"] = self.pressure()
return out
class PrepumpSystem(Assembly):
"""The whole Bernina prepump system: one Roots pump, the common pump-line
gauge ``Gp``, and up to five :class:`PrepumpLine` exits.
gauge ``Gp``, and any number of :class:`PrepumpLine` channels.
The pump/vent *procedures* live here because they must coordinate all lines
(isolate the others while one pumps, restore them afterwards -- the spec's
``P2-Pn``/``V2-Vn`` columns).
The pump-down/vent *procedures* live here because they must coordinate
all channels (isolate the others while one is pumped, restore them
afterwards).
Parameters
----------
@@ -270,19 +100,25 @@ class PrepumpSystem(Assembly):
roots_pump : str
PV base of the Roots (backing) pump.
lines : dict[str, PrepumpLine | dict]
The exits, keyed by name. Each value is either a ready
:class:`PrepumpLine` or a **plain dict of its keyword args** (``kind``,
``valve_prevac``, ``valve_vent``, ``gauge``, ``turbo``, ...). The dict
form is what lets the whole system be described by one editable config
literal -- see :data:`BERNINA_PREPUMP_CONFIG` / :func:`make_prepump_system`.
The channels, keyed by name. Each value is either a ready
:class:`PrepumpLine` or a **plain dict of its keyword args**
(``gauge``, ``valve_prevac``, ``valve_vent``). The dict form is
what lets the whole system be described by one editable config
literal -- see :data:`BERNINA_PREPUMP_CONFIG` /
:func:`make_prepump_system`.
p_target : float
Pressure [mbar] at/below which a gauge counts as "pumped" (spec ``1e-3``).
Pressure [mbar] at/below which a gauge counts as "pumped".
p_vent_target : float
Pressure [mbar] at/above which a channel counts as "vented" (close
enough to atmosphere -- tune to what the channel's own gauge can
actually read up to).
"""
def __init__(self, name=None, gp=None, roots_pump=None, lines=None,
p_target=1e-3, vent_line_name="GN2"):
p_target=1e-3, p_vent_target=500.0, vent_line_name="GN2"):
super().__init__(name=name)
self.p_target = p_target
self.p_vent_target = p_vent_target
self.vent_line_name = vent_line_name
if roots_pump is not None:
self._append(PrePump, roots_pump, name="roots_pump", is_status=True)
@@ -310,99 +146,91 @@ class PrepumpSystem(Assembly):
raise KeyError(f"no prepump line named {line!r}")
return got
def _pressure(self, gauge_obj):
def gp_pressure(self):
"""Common pump-line pressure (Gp), or None."""
gp = getattr(self, "gp", None)
if gp is None:
return None
try:
return gauge_obj.pressure.get_current_value()
return gp.pressure.get_current_value()
except Exception:
return None
def _is_pumped(self, pressure):
return pressure is not None and pressure <= self.p_target
def gp_pressure(self):
"""Common pump-line pressure (Gp), or None."""
gp = getattr(self, "gp", None)
return None if gp is None else self._pressure(gp)
def _is_vented(self, pressure):
return pressure is not None and pressure >= self.p_vent_target
# ---- procedures ----------------------------------------------------
def _isolate_others(self, active):
for line in self.lines:
if line is not active:
try:
line.isolate()
except Exception as e:
print(f" (could not isolate {line.name}: {e})")
# ---- procedures ------------------------------------------------------
def pump_down(self, line, timeout=300.0, poll=1.0):
"""Pump down one channel.
def _restore_others(self, active):
for line in self.lines:
if line is not active:
try:
line.restore()
except Exception as e:
print(f" (could not restore {line.name}: {e})")
def pump_down(self, line, wait=True, timeout=300.0, poll=2.0):
"""Pump down one line.
Sequence (spec tables): isolate every *other* line, drive this line to
``pump_down``, then watch ``Gp`` and this line's ``G``:
* both reach the target -> **success**: this line -> ``connected``,
other lines restored (their pump valves reopen);
* ``Gp`` recovers but ``G`` stays high, or `timeout` elapses -> **failed**:
this line -> ``isolated``, other lines restored.
With ``wait=False`` it only commands the initial ``pump_down`` state and
returns immediately (no monitoring).
Close its vent valve, isolate every *other* channel (close their
pump valves, so they don't get pumped against the rising ``Gp``),
then open this channel's pump valve and wait for both ``Gp`` and its
own gauge to reach ``p_target``. Reopens the other channels'
pump valves again either way (success or timeout). Returns ``True``
on success, ``False`` if `timeout` elapses first.
"""
line = self._get_line(line)
print(f"[prepump] pumping down '{line.name}' ({line.kind}); isolating other lines")
self._isolate_others(line)
line.set_state("pump_down")
if not wait:
return None
others = [l for l in self.lines if l is not line]
print(f"[prepump] pump down '{line.name}': isolating other channels")
for other in others:
other.valve_prevac.close()
line.valve_vent.close()
line.valve_prevac.open()
t0 = time.time()
while time.time() - t0 < timeout:
gp = self.gp_pressure()
g = line.pressure()
if self._is_pumped(gp) and self._is_pumped(g):
print(f"[prepump] '{line.name}' pumped (Gp={gp}, G={g}) -> connected")
line.set_state("connected")
self._restore_others(line)
return "success"
while not (self._is_pumped(self.gp_pressure()) and self._is_pumped(line.pressure())):
if time.time() - t0 > timeout:
print(f"[prepump] '{line.name}' pump down FAILED after {timeout}s "
f"(Gp={self.gp_pressure()}, G={line.pressure()}) -- isolating")
line.valve_prevac.close()
for other in others:
other.valve_prevac.open()
return False
time.sleep(poll)
gp = self.gp_pressure()
g = line.pressure()
print(f"[prepump] '{line.name}' pumpdown FAILED (Gp={gp}, G={g}) -> isolated")
line.set_state("isolated")
self._restore_others(line)
return "failed"
def vent(self, line, turbo_spundown=None):
"""Vent one line through the GN2 vent line.
print(f"[prepump] '{line.name}' pumped down (Gp={self.gp_pressure()}, G={line.pressure()})")
for other in others:
other.valve_prevac.open()
return True
For ``turbo``/``vent_access`` lines the turbo must be spun down first
(the spec's "after turbo spindown"); ``prepump_access`` lines keep the
turbo spinning (its access valve ``T`` closes instead). Pass
``turbo_spundown=True`` to confirm you've handled the turbo when this
line has one and isn't a ``prepump_access`` line.
def vent(self, line, timeout=300.0, poll=1.0):
"""Vent one channel to atmosphere through the GN2 vent line.
Close its pump valve, open its vent valve, and wait for its own
gauge to reach ``p_vent_target``, then close the vent valve again.
Returns ``True`` on success, ``False`` if `timeout` elapses first.
# planned, once the vent line's flow meter Fv exists: open at full
# flow first, then throttle down as the channel nears atmosphere
# (see the spec's "low overpressure, limited flow" GN2 vent line);
# for now the vent valve is simply open, then closed.
"""
line = self._get_line(line)
needs_spindown = line.kind in ("turbo", "vent_access") and getattr(line, "turbo", None) is not None
if needs_spindown and not turbo_spundown:
raise RuntimeError(
f"'{line.name}' has a turbo: spin it down first "
f"(e.g. {line.name}.turbo.stop()), then call "
f"vent('{line.name}', turbo_spundown=True)."
)
print(f"[prepump] venting '{line.name}' via {self.vent_line_name} vent line")
self._restore_others(line)
line.set_state("venting")
return "venting"
print(f"[prepump] venting '{line.name}'")
line.valve_prevac.close()
line.valve_vent.open()
t0 = time.time()
while not self._is_vented(line.pressure()):
if time.time() - t0 > timeout:
print(f"[prepump] '{line.name}' venting FAILED after {timeout}s (G={line.pressure()})")
line.valve_vent.close()
return False
time.sleep(poll)
print(f"[prepump] '{line.name}' vented (G={line.pressure()})")
line.valve_vent.close()
return True
def isolate_all(self):
"""Safe state: close every line off from pump and vent lines."""
"""Safe state: close every channel off from pump and vent lines."""
for line in self.lines:
try:
line.isolate()
@@ -417,18 +245,19 @@ class PrepumpSystem(Assembly):
def check(self, verbose=True):
"""Diagnose which configured components are missing or failed to
connect, at *every* depth (roots pump, ``Gp``, and every line's
gauge/turbo/valves).
connect, at *every* depth (roots pump, ``Gp``, and every channel's
gauge/valves).
A component that fails to connect (e.g. a typo'd or unreachable PV)
does **not** raise -- it's swallowed where it happens and left as a
``FailedComponent`` placeholder (see ``Assembly._append(optional=True)``).
``Assembly._append`` now mirrors that failure up through every ancestor
too (so e.g. ``prepump.get_status()`` correctly reports a failure buried
inside a line's own valve/gauge/turbo, not just direct children) -- this
method is the complementary, explicit form: a live re-probe of every
configured component by path, in one table, including ones that were
simply never given a PV (``"not configured"``, which isn't a failure).
``Assembly._append`` mirrors that failure up through every ancestor
too (so e.g. ``prepump.get_status()`` correctly reports a failure
buried inside a channel's own valve/gauge, not just direct
children) -- this method is the complementary, explicit form: a live
re-probe of every configured component by path, in one table,
including ones that were simply never given a PV (``"not configured"``,
which isn't a failure).
Returns a list of ``(path, status, detail)`` with ``status`` one of
``"ok"``, ``"FAILED"``, ``"not configured"``; prints a table if
@@ -454,9 +283,8 @@ class PrepumpSystem(Assembly):
for lname in self._line_names:
line = getattr(self, lname)
probe(f"{lname}.gauge", getattr(line, "gauge", None))
probe(f"{lname}.turbo", getattr(line, "turbo", None))
for role in line._roles:
probe(f"{lname}.{role}", getattr(line, role, None))
probe(f"{lname}.valve_prevac", getattr(line, "valve_prevac", None))
probe(f"{lname}.valve_vent", getattr(line, "valve_vent", None))
if verbose:
for path, status, detail in rows:
@@ -481,8 +309,8 @@ class PrepumpSystem(Assembly):
open/closed state and every gauge's alarm severity is cheap; revisit
if that stops being true) colours valves green/red by open/closed
state and gauges green/red by live EPICS alarm severity (touches
EPICS); pass `live=False` for the plain kind-coloured, EPICS-free
version. See :func:`build_prepump_svg`."""
EPICS); pass `live=False` for the plain, EPICS-free version. See
:func:`build_prepump_svg`."""
import os
import tempfile
@@ -502,7 +330,7 @@ class PrepumpSystem(Assembly):
def svg_panel(self, in_window=False, live=True, exclude_group_ids=None):
"""Open the clickable prepump schematic in the interactive viewer
(Jupyter cell, or a native Qt window with ``in_window=True``). Clicking a
valve/gauge/pump inspects that device; clicking a line's *pump*/*vent*
valve/gauge/pump inspects that device; clicking a channel's *pump*/*vent*
label, or a valve's small green/red open/close dot, runs the
corresponding action against this system. `live=True` (default)
colours valves/gauges by their current state (touches EPICS); this is
@@ -522,6 +350,23 @@ def _valve_open_state(valve):
return None
#: the two common lines' colours -- pump line (to the Roots pump) black,
#: vent line (to the GN2 vent) blue.
_PUMP_COLOR = "#1a1a1a"
_VENT_COLOR = "#1f4e8c"
def _fmt_pressure(p):
"""Compact scientific-notation string for a gauge reading, or "?" if
`p` is None/unreadable."""
if p is None:
return "?"
try:
return f"{p:.1e}"
except Exception:
return "?"
def _gauge_ok_state(gauge):
"""True/False/None: is `gauge` (a VacuumGauge) reading in range (EPICS
alarm severity NO_ALARM), in alarm (MINOR/MAJOR, i.e. some HIHI/LOLO/HIGH/
@@ -540,17 +385,27 @@ def _gauge_ok_state(gauge):
def build_prepump_svg(system, live=False):
"""Render `system` as a P&ID-style clickable SVG string, mirroring the spec
figures: Roots pump -> common pump line (with Gp) + GN2 vent line, and one
vertical branch per line with its pump/vent valves, gauge and turbo. Clicks
carry ``onclick="// eco: <path>"`` markers resolved against the system alias
by :mod:`eco.utilities.svg_interactor`. `live=True` colours each valve
"""Render `system` as a P&ID-style clickable SVG string, mirroring the
spec figure's own orientation: each channel is drawn top-down as it would
be plumbed -- channel label at the top (a not-yet-modelled chamber would
connect there), its gauge just below, then its valves, down to the common
Roots pump line (with Gp) and GN2 vent line at the bottom. Clicks carry
``onclick="// eco: <path>"`` markers resolved against the system alias by
:mod:`eco.utilities.svg_interactor`. `live=True` colours each valve
green/red by open/closed state and each gauge green/red by its live EPICS
alarm severity (touches EPICS); default is the plain kind colour only."""
alarm severity (touches EPICS); default is the plain, EPICS-free version."""
from eco.xoptics.beamline_svg import _symbol, _esc
def _short(role):
return role.replace("valve_", "")
#: panel background colour, repeated here (matches the `<rect>` fill
#: below) as an opaque disc behind every device glyph -- `_symbol`'s
#: unicode glyphs (Ⓟ/⧔/⊚) are just outline strokes, so without this the
#: common pump/vent lines passing behind a channel's icons show through
#: their middle instead of looking like they end at the icon.
_PANEL_BG = "#f7f8fa"
def _opaque_symbol(kind, cx, cy, r, color, state):
return (f'<circle cx="{cx}" cy="{cy}" r="{r+3}" fill="{_PANEL_BG}"/>'
+ _symbol(kind, cx, cy, r, color, state))
line_names = system._line_names
col_w = 190
@@ -558,24 +413,20 @@ def build_prepump_svg(system, live=False):
x0 = margin + 120 # room for the roots pump on the left
# +160 on the right for the Gp gauge and the "GN2 vent line" label
width = x0 + max(1, len(line_names)) * col_w + 160
pump_y = 90
vent_y = 150
turbo_y = 250
gauge_y = 330
label_y = 375
btn_y = 395
height = btn_y + 60
label_y = 68
gauge_y = 115
pump_y = 195
vent_y = 255
btn_y = vent_y + 35
height = btn_y + 55
def _valve_buttons(cmd_prefix, vx, vy, r):
"""Small open/close dots pinned right next to a valve glyph at
(vx, vy) of radius `r` -- offset just clear of the glyph itself
(dx = r + 9, so even the largest glyph here (r=13) keeps the closest
dot edge a few px away) and stacked vertically (dy = +-7) rather than
sideways, since valves can sit only 50px apart horizontally
(staggered pump-side pairs) but always have >=60px of clear space
above/below along their own column. No visible text (no room to set
it legibly at this size) -- colour (green/red) plus a `<title>`
hover tooltip carry the meaning, consistent with the glyphs above."""
(dx = r + 9) and stacked vertically (dy = +-7). No visible text (no
room to set it legibly at this size) -- colour (green/red) plus a
`<title>` hover tooltip carry the meaning, consistent with the
glyphs above."""
bx = vx + r + 9
s = []
for dy, cmd, col in ((-7, f"{cmd_prefix}.open()", "#2e7d32"),
@@ -597,26 +448,32 @@ def build_prepump_svg(system, live=False):
f'<tspan font-size="12" font-weight="normal" fill="#6b7280">(click a device to inspect; '
f'click pump/vent, or a valve\'s small green/red dot, to run)</tspan></text>'
)
# common pump line + vent line
# common pump line (black) + vent line (blue)
x_end = x0 + len(line_names) * col_w
P.append(f'<line x1="{x0-40}" y1="{pump_y}" x2="{x_end}" y2="{pump_y}" stroke="#1f4e8c" stroke-width="3"/>')
P.append(f'<line x1="{x0-40}" y1="{vent_y}" x2="{x_end+70}" y2="{vent_y}" stroke="#555" stroke-width="2"/>')
P.append(f'<text x="{x_end+6}" y="{vent_y-6}" font-size="11" fill="#555">{_esc(system.vent_line_name)} vent line</text>')
P.append(f'<line x1="{x0-40}" y1="{pump_y}" x2="{x_end}" y2="{pump_y}" stroke="{_PUMP_COLOR}" stroke-width="3"/>')
P.append(f'<line x1="{x0-40}" y1="{vent_y}" x2="{x_end+70}" y2="{vent_y}" stroke="{_VENT_COLOR}" stroke-width="2"/>')
P.append(f'<text x="{x_end+6}" y="{vent_y-6}" font-size="11" fill="{_VENT_COLOR}">{_esc(system.vent_line_name)} vent line</text>')
# planned: flow meter Fv on the vent line, once it exists as a device --
# e.g. right after the last channel's branch:
# fx = x_end + 70
# P.append(_symbol("flowmeter", fx, vent_y, 11, _VENT_COLOR, None))
# P.append(f'<text x="{fx}" y="{vent_y+18}" text-anchor="middle" font-size="10">Fv</text>')
# Roots pump (custom symbol) + Gp
rpx, rpy = margin + 40, pump_y
P.append(f'<g style="cursor:pointer" onclick="// eco: roots_pump"><desc>roots_pump</desc><title>roots_pump</title>')
P.append(f'<circle cx="{rpx}" cy="{rpy}" r="26" fill="white" stroke="#1f4e8c" stroke-width="2.5"/>')
P.append(f'<text x="{rpx}" y="{rpy+6}" text-anchor="middle" font-size="18" fill="#1f4e8c">R</text>')
P.append(f'<circle cx="{rpx}" cy="{rpy}" r="26" fill="white" stroke="{_PUMP_COLOR}" stroke-width="2.5"/>')
P.append(f'<text x="{rpx}" y="{rpy+6}" text-anchor="middle" font-size="18" fill="{_PUMP_COLOR}">R</text>')
P.append(f'<text x="{rpx}" y="{rpy+42}" text-anchor="middle" font-size="11" fill="#2e3440">roots_pump</text>')
P.append('</g>')
P.append(f'<line x1="{rpx+26}" y1="{pump_y}" x2="{x0-40}" y2="{pump_y}" stroke="#1f4e8c" stroke-width="3"/>')
P.append(f'<line x1="{rpx+26}" y1="{pump_y}" x2="{x0-40}" y2="{pump_y}" stroke="{_PUMP_COLOR}" stroke-width="3"/>')
if getattr(system, "gp", None) is not None:
gx = x_end + 30
gp_label = _fmt_pressure(system.gp_pressure()) if live else "Gp"
P.append(f'<g style="cursor:pointer" onclick="// eco: gp"><desc>gp</desc><title>gp (Gp)</title>')
P.append(_symbol("gauge", gx, pump_y, 13, "#9467bd", _gauge_ok_state(system.gp) if live else None))
P.append(f'<text x="{gx}" y="{pump_y-20}" text-anchor="middle" font-size="11" fill="#2e3440">Gp</text>')
P.append(_opaque_symbol("gauge", gx, pump_y, 13, "#9467bd", _gauge_ok_state(system.gp) if live else None))
P.append(f'<text x="{gx}" y="{pump_y-20}" text-anchor="middle" font-size="11" fill="#2e3440">{_esc(gp_label)}</text>')
P.append('</g>')
P.append(f'<line x1="{x_end}" y1="{pump_y}" x2="{gx}" y2="{pump_y}" stroke="#1f4e8c" stroke-width="3"/>')
P.append(f'<line x1="{x_end}" y1="{pump_y}" x2="{gx}" y2="{pump_y}" stroke="{_PUMP_COLOR}" stroke-width="3"/>')
def clickable(cmd, title, inner, cx, label, ly):
s = [f'<g style="cursor:pointer" onclick="// eco: {_esc(cmd)}"><desc>{_esc(cmd)}</desc><title>{_esc(title)}</title>']
@@ -628,45 +485,32 @@ def build_prepump_svg(system, live=False):
for i, lname in enumerate(line_names):
line = getattr(system, lname)
cx = x0 + i * col_w + col_w / 2
# branch connector down from the pump line
P.append(f'<line x1="{cx}" y1="{pump_y}" x2="{cx}" y2="{gauge_y}" stroke="#888" stroke-width="1.5"/>')
# pump-side valve(s) on the pump line, vent-side valve(s) on the vent line
pump_roles = [r for r in line._valve_names if r in _PUMP_SIDE_ROLES]
vent_roles = [r for r in line._valve_names if r in _VENT_SIDE_ROLES]
other_roles = [r for r in line._valve_names if r not in _PUMP_SIDE_ROLES and r not in _VENT_SIDE_ROLES]
for j, role in enumerate(pump_roles):
vx = cx + (j - (len(pump_roles) - 1) / 2) * 50
# stagger labels of side-by-side pump valves so they don't overlap
ly = pump_y - 18 - (18 if (len(pump_roles) > 1 and j % 2 == 0) else 0)
vstate = _valve_open_state(getattr(line, role)) if live else None
P.append(clickable(f"{lname}.{role}", f"{lname}.{role}",
_symbol("valve", vx, pump_y, 11, "#8c564b", vstate), vx, _short(role), ly))
P.append(_valve_buttons(f"{lname}.{role}", vx, pump_y, 11))
for role in vent_roles:
vstate = _valve_open_state(getattr(line, role)) if live else None
P.append(clickable(f"{lname}.{role}", f"{lname}.{role}",
_symbol("valve", cx, vent_y, 11, "#8c564b", vstate), cx, _short(role), vent_y - 16))
P.append(_valve_buttons(f"{lname}.{role}", cx, vent_y, 11))
# any remaining roles (e.g. turbo_access T) drawn between vent line and turbo
for k, role in enumerate(other_roles):
oy = vent_y + 34 + k * 30
vstate = _valve_open_state(getattr(line, role)) if live else None
P.append(clickable(f"{lname}.{role}", f"{lname}.{role}",
_symbol("valve", cx, oy, 10, "#8c564b", vstate), cx, _short(role), oy - 15))
P.append(_valve_buttons(f"{lname}.{role}", cx, oy, 10))
# turbo pump (if any)
if getattr(line, "turbo", None) is not None:
P.append(clickable(f"{lname}.turbo", f"{lname}.turbo",
_symbol("pump", cx, turbo_y, 15, "#7f7f7f", None), cx, "turbo", turbo_y + 26))
# line gauge
# channel label at the top -- stands in for the (not modelled) chamber
P.append(f'<text x="{cx}" y="{label_y}" text-anchor="middle" font-size="12" font-weight="bold" fill="#2e3440">{_esc(lname)}</text>')
# dashed stub above the gauge: this channel connects to its chamber up here
P.append(f'<line x1="{cx}" y1="{label_y+10}" x2="{cx}" y2="{gauge_y-16}" '
f'stroke="#aaa" stroke-width="1.5" stroke-dasharray="3,3"/>')
# branch stem down from the gauge through the valves to the common lines
P.append(f'<line x1="{cx}" y1="{gauge_y}" x2="{cx}" y2="{vent_y}" stroke="#888" stroke-width="1.5"/>')
# channel gauge, right below the chamber connection -- its live
# pressure reading is the label, on this upper side of the branch
if getattr(line, "gauge", None) is not None:
gstate = _gauge_ok_state(line.gauge) if live else None
glabel = _fmt_pressure(line.pressure()) if live else "G"
P.append(clickable(f"{lname}.gauge", f"{lname}.gauge (G)",
_symbol("gauge", cx, gauge_y, 13, "#9467bd", gstate), cx, "G", gauge_y + 24))
# line label + kind
P.append(f'<text x="{cx}" y="{label_y}" text-anchor="middle" font-size="12" font-weight="bold" fill="#2e3440">{_esc(lname)}</text>')
P.append(f'<text x="{cx}" y="{label_y+13}" text-anchor="middle" font-size="9" fill="#6b7280">{_esc(line.kind)}</text>')
# pump / vent action "buttons"
_opaque_symbol("gauge", cx, gauge_y, 13, "#9467bd", gstate), cx, glabel, gauge_y - 20))
# pump valve on the pump line, vent valve on the vent line (both below)
if getattr(line, "valve_prevac", None) is not None:
vstate = _valve_open_state(line.valve_prevac) if live else None
P.append(clickable(f"{lname}.valve_prevac", f"{lname}.valve_prevac",
_opaque_symbol("valve", cx, pump_y, 11, "#8c564b", vstate), cx, "prevac", pump_y - 18))
P.append(_valve_buttons(f"{lname}.valve_prevac", cx, pump_y, 11))
if getattr(line, "valve_vent", None) is not None:
vstate = _valve_open_state(line.valve_vent) if live else None
P.append(clickable(f"{lname}.valve_vent", f"{lname}.valve_vent",
_opaque_symbol("valve", cx, vent_y, 11, "#8c564b", vstate), cx, "vent", vent_y - 16))
P.append(_valve_buttons(f"{lname}.valve_vent", cx, vent_y, 11))
# pump / vent action "buttons", below the common lines
for bx, blabel, cmd, col in (
(cx - 40, "pump", f"pump_down('{lname}')", "#2e7d32"),
(cx + 4, "vent", f"vent('{lname}')", "#c62828"),
@@ -693,16 +537,12 @@ def make_prepump_system(config, name="prepump"):
"gp": "<Gp gauge PV>", # common prevac-line gauge
"roots_pump": "<roots pump PV>",
"p_target": 1e-3, # optional, mbar (default 1e-3)
"p_vent_target": 500.0, # optional, mbar (default 500.0)
"lines": {
"<line name>": {
"kind": "turbo" | "transport" | "vent_access" | "prepump_access",
"gauge": "<G PV>", # this line's gauge
"turbo": "<turbo PV>", # optional turbo it serves
"<channel name>": {
"gauge": "<G PV>", # this channel's gauge
"valve_prevac": "<P PV>", # -> prevac/roots line
"valve_vent": "<V PV>", # -> GN2 vent line
# prepump_access only:
"valve_turbo_prevac": "<P1 PV>",
"valve_turbo_access": "<T PV>",
},
...
},
@@ -721,55 +561,37 @@ def make_prepump_system(config, name="prepump"):
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),
)
# --------------------------------------------------------------------------
# Bernina concrete config -- PV NAMES ARE PLACEHOLDERS, FILL THESE IN.
# Edit this dict as a whole (here or copied into eco/bernina/bernina.py) and
# hand it to make_prepump_system(). Line *kinds* are a GUESS (the spec's
# "usage scenarios for permanent lines 1-2" is truncated) -- adjust once known.
# hand it to make_prepump_system().
# --------------------------------------------------------------------------
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]
"lines": {
# permanent dual-access chambers (GUESS: prepump_access) -------------
"line1": {
"kind": "prepump_access",
"gauge": None, # G1 gauge base
"turbo": None, # turbo pump base
"valve_prevac": None, # P2 chamber roughing valve
"valve_vent": None, # V2 chamber vent valve
"valve_turbo_prevac": None, # P1 turbo backing valve
"valve_turbo_access": None, # T turbo isolation valve
},
"line2": {
"kind": "prepump_access",
"gauge": None, "turbo": None,
"valve_prevac": None, "valve_vent": None,
"valve_turbo_prevac": None, "valve_turbo_access": None,
},
# classic turbo prepump lines (GUESS: turbo) ------------------------
"line3": {"kind": "turbo", "gauge": None, "turbo": None,
"valve_prevac": None, "valve_vent": None},
"line4": {"kind": "turbo", "gauge": None, "turbo": None,
"valve_prevac": None, "valve_vent": None},
# beam-transport pipe, pre-vacuum only (GUESS: transport) -----------
"line5": {"kind": "transport", "gauge": None,
"valve_prevac": None, "valve_vent": None},
"line1": {"gauge": None, "valve_prevac": None, "valve_vent": None},
"line2": {"gauge": None, "valve_prevac": None, "valve_vent": None},
# further channels, not yet cabled:
# "line3": {"gauge": None, "valve_prevac": None, "valve_vent": None},
# "line4": {"gauge": None, "valve_prevac": None, "valve_vent": None},
},
}
def make_bernina_prepump_system(name="prepump"):
"""Build the 5-line Bernina prepump system from :data:`BERNINA_PREPUMP_CONFIG`.
"""Build the Bernina prepump system from :data:`BERNINA_PREPUMP_CONFIG`.
All PVs there are ``None`` placeholders: fill them in (in the dict above, or
in a copy of it in ``bernina.py``) then this returns a ready
:class:`PrepumpSystem`. A line whose PVs are still ``None`` instantiates with
its components simply absent, so the object is usable for wiring/UI work
before the PVs exist.
:class:`PrepumpSystem`. A channel whose PVs are still ``None`` instantiates
with its components simply absent, so the object is usable for
wiring/UI work before the PVs exist.
"""
return make_prepump_system(BERNINA_PREPUMP_CONFIG, name=name)
+129 -7
View File
@@ -50,6 +50,19 @@ tests/test_camserver_stream_qt.py). GUI mouse-interaction and the actual
image widgets are not (no display in CI); they're kept thin wrappers
around that tested core.
Resolving "the" pipeline for a camera: kind="camera_pipeline" takes a raw
camera name and auto-resolves it to its own default processing pipeline
(creating the pipeline config on the fly if needed) rather than either the
camera's raw stream (kind="camera") or requiring the caller to already know
a pipeline instance name (kind="pipeline") -- see resolve_camera_pipeline,
which mirrors decompiled logic from
ch.psi.pshell.screenpanel.CamServerViewer.setStream's "Cameras" selection
mode. This is what eco.devices_general.cameras_swissfel.CameraBasler/
CameraPCO's own .viewer() uses, passing cam=<the camera Assembly> so the
viewer can add a "Camera Settings" button (opens cam.widget(normal=True),
the normal property-grid widget) -- mirrors
eco.widgets.camera_stream_qt.AxisPTZStreamQt's own "Settings" button.
Embedding (for eco.widgets.camserver_panel_qt): with embed=True the
window is frameless and, once shown, prints "WINID <id>" (its native
window id) to stdout -- the panel process picks that up and reparents the
@@ -77,15 +90,72 @@ _app_ref = None # keep a strong reference to any QApplication we create ourselv
BERNINA_PREFIXES = ("SARES", "SAROP", "SLAAR", "SARFE")
# The pipeline-name convention pshell's own screen panel uses to go from a
# raw camera name to "the" processing pipeline for it -- decompiled from
# ch.psi.pshell.screenpanel.CamServerViewer's `pipelineNameFormat` field
# (default "%s_sp", i.e. Python's "{}_sp") and its getPipelineName(camera) =
# String.format(pipelineNameFormat, camera). See resolve_camera_pipeline.
DEFAULT_PIPELINE_NAME_FORMAT = "{}_sp"
def default_pipeline_name(camera_name, name_format=DEFAULT_PIPELINE_NAME_FORMAT):
"""The "screenpanel" pipeline name pshell derives from a raw camera name
by default -- e.g. "SARES20-PROF141-M1" -> "SARES20-PROF141-M1_sp". See
DEFAULT_PIPELINE_NAME_FORMAT."""
return name_format.format(camera_name)
def resolve_camera_pipeline(
camera_name, pipeline_url=None, create=True, name_format=DEFAULT_PIPELINE_NAME_FORMAT
):
"""Resolve "the" processing pipeline for a raw camera name -- what a
camera's own .viewer() uses so callers never have to know or guess a
pipeline instance name themselves.
This is the piece pshell's screen panel has that eco's own
resolve_stream(kind="pipeline") doesn't: given just a camera name, it
doesn't merely reuse-or-create a *running instance* of an
already-existing same-named pipeline config (what create=True already
does below) -- it first works out *which* pipeline config that even is
(default_pipeline_name), and if no such config exists yet either, it
creates one on the fly. Decompiled from
ch.psi.pshell.screenpanel.CamServerViewer.setStream's "Cameras"
selection-mode branch:
pipelineName = getPipelineName(cameraName) # "{cam}_sp"
if pipelineName not in server.getPipelines():
server.savePipelineConfig(pipelineName, {"camera_name": cameraName})
server.start(pipelineName, instanceName) # create/reuse
Returns (pipeline_name, stream_address).
"""
from cam_server import PipelineClient
client = PipelineClient(pipeline_url) if pipeline_url else PipelineClient()
pipeline_name = default_pipeline_name(camera_name, name_format=name_format)
try:
return pipeline_name, client.get_instance_stream(pipeline_name)
except Exception:
if not create:
raise
if pipeline_name not in client.get_pipelines():
client.save_pipeline_config(pipeline_name, {"camera_name": camera_name})
_, stream = client.create_instance_from_name(pipeline_name)
return pipeline_name, stream
def resolve_stream(name, kind="pipeline", pipeline_url=None, camera_url=None, create=True):
"""Resolve a cam_server camera or pipeline instance name to a bsread
stream address ("tcp://host:port"), via the same REST calls pshell's
ch.psi.pshell.camserver.PipelineSource/CameraSource use.
kind: "pipeline" or "camera".
create: for a pipeline, start a new instance from the pipeline config
of the same name if no running instance is found (mirrors
CamServerViewer's own selectCamera->initialize behavior).
kind: "pipeline", "camera", or "camera_pipeline" (a raw camera name,
auto-resolved to its own default processing pipeline -- see
resolve_camera_pipeline -- rather than the camera's own raw,
unprocessed stream that kind="camera" gives you).
create: for a pipeline (or camera_pipeline), start a new instance from
the pipeline config of the same name if no running instance is
found (mirrors CamServerViewer's own selectCamera->initialize
behavior).
"""
from cam_server import CamClient, PipelineClient
@@ -93,6 +163,10 @@ def resolve_stream(name, kind="pipeline", pipeline_url=None, camera_url=None, cr
client = CamClient(camera_url) if camera_url else CamClient()
return client.get_instance_stream(name)
if kind == "camera_pipeline":
_, stream = resolve_camera_pipeline(name, pipeline_url=pipeline_url, create=create)
return stream
client = PipelineClient(pipeline_url) if pipeline_url else PipelineClient()
try:
return client.get_instance_stream(name)
@@ -830,6 +904,7 @@ class CamServerStreamQt:
rate_hz=10.0,
theme=None,
auto_start=True,
cam=None,
):
self.name = name
self.kind = kind
@@ -838,6 +913,13 @@ class CamServerStreamQt:
self.embed = embed
self.demo_color = demo_color
self.theme = theme # "dark" | "light" | None -- see eco.widgets.qt_theme
# the eco Assembly (e.g. CameraBasler/CameraPCO) this viewer was
# opened from, if any -- see cam.viewer()/_default_widget = "viewer".
# Only used to add a "Camera Settings" button (see _open_settings),
# mirroring eco.widgets.camera_stream_qt.AxisPTZStreamQt's own
# "Settings" button/cam parameter.
self.cam = cam
self._settings_window = None
self.window = None
self._worker = None
self._processor = FrameProcessor()
@@ -982,6 +1064,20 @@ class CamServerStreamQt:
view_bar.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
view_bar.setMovable(False)
if self.cam is not None:
# only present when this viewer was opened from a real eco
# camera Assembly (cam.viewer()), not e.g. the standalone CLI --
# named "Camera Settings" rather than plain "Settings" to avoid
# clashing with the dock-visibility "Settings" action in
# bg_bar below (a different thing: this opens the device's own
# plain property-grid widget, mirroring
# eco.widgets.camera_stream_qt.AxisPTZStreamQt's "Settings"
# button -- see _open_settings)
settings_btn = QtWidgets.QAction("Camera Settings", self.window)
settings_btn.triggered.connect(self._open_settings)
view_bar.addAction(settings_btn)
view_bar.addSeparator()
self._pause_btn = QtWidgets.QAction("Pause", self.window)
self._pause_btn.setCheckable(True)
self._pause_btn.toggled.connect(self._on_pause_toggled)
@@ -1260,6 +1356,19 @@ class CamServerStreamQt:
self._cal_scale_y = dialog.scale_y
self._cal_unit = dialog.unit
def _open_settings(self):
# normal=True: this button specifically wants the plain property
# grid -- without it, since CameraBasler/CameraPCO set
# _default_widget = "viewer", plain self.cam.widget() would just
# reopen this same live viewer instead of the settings widget (see
# Assembly.widget()'s normal= docstring, and
# eco.widgets.camera_stream_qt.AxisPTZStreamQt._open_settings,
# which this mirrors)
#
# keep a reference so the window (and its poll thread) isn't
# garbage-collected as soon as this method returns
self._settings_window = self.cam.widget(normal=True)
def _on_histogram_levels_changed(self, vmin, vmax):
# dragging a handle on the histogram/colorscale sidebar implies
# "I want manual contrast with exactly these bounds" -- switch
@@ -1510,24 +1619,37 @@ class CamServerStreamQt:
def make_camserver_stream_qt(
name, kind="pipeline", pipeline_url=None, camera_url=None, theme=None, auto_start=True
name,
kind="pipeline",
pipeline_url=None,
camera_url=None,
rate_hz=10.0,
theme=None,
auto_start=True,
cam=None,
):
"""Convenience factory, mirrors make_axisptz_qt_window's signature.
theme: "dark" | "light" | None (native) -- see eco.widgets.qt_theme."""
theme: "dark" | "light" | None (native) -- see eco.widgets.qt_theme.
cam: the eco camera Assembly this viewer belongs to, if any -- adds a
"Camera Settings" button (see CamServerStreamQt._open_settings)."""
return CamServerStreamQt(
name,
kind=kind,
pipeline_url=pipeline_url,
camera_url=camera_url,
rate_hz=rate_hz,
theme=theme,
auto_start=auto_start,
cam=cam,
)
def _main(argv=None):
parser = argparse.ArgumentParser(description="cam_server / demo live image viewer")
parser.add_argument("name", help="camera or pipeline instance name (ignored for --kind demo)")
parser.add_argument("--kind", choices=["pipeline", "camera", "demo"], default="pipeline")
parser.add_argument(
"--kind", choices=["pipeline", "camera", "camera_pipeline", "demo"], default="pipeline"
)
parser.add_argument("--pipeline-url", default=None)
parser.add_argument("--camera-url", default=None)
parser.add_argument(
+109 -7
View File
@@ -318,11 +318,33 @@ class _NamespaceLauncher(QtWidgets.QWidget):
# every tick, whether or not anything actually changed).
self._list.blockSignals(True)
try:
entries = sorted_namespace_entries(self.namespace)
# Reconcile against real state before drawing anything: a name
# in self._loading (single-click init, or part of an Init All
# batch) whose state has actually moved past "lazy" is done,
# whether or not the thread that did it has gotten around to
# emitting its own completion signal yet. This is what lets
# entries stop spinning -- and become clickable again, see
# open_by_name's `name in self._loading` guard -- one by one as
# Init All works through them, instead of all at once only when
# the whole batch finishes (init_all() itself doesn't report
# per-item progress, just a single call that blocks until every
# name in the batch is done). Only ever removes names, and only
# ever from here, not from the individual-click path's own
# _on_init_done bridge signal handler -- both discard() the
# same set, so whichever notices first wins; harmless either
# way since discard() on an absent name is a no-op. Deliberately
# does NOT call on_open here (unlike _on_init_done) -- opening a
# dozen widgets at once mid-batch would be exactly the
# surprise _on_init_all_clicked's docstring says to avoid.
states = dict(entries)
self._loading -= {name for name in self._loading if states.get(name, "lazy") != "lazy"}
query = self._filter_edit.text().strip().lower()
self._list.setRowCount(0)
lazy_count = 0
required = self._required_names()
for name, state in sorted_namespace_entries(self.namespace):
for name, state in entries:
if state == "lazy":
lazy_count += 1
if query and query not in name.lower():
@@ -568,14 +590,16 @@ class _DesktopMainWindow(QtWidgets.QMainWindow):
class EcoDesktopApp:
"""The desktop workbench window: an embedded IPython console (central
widget) plus a "Namespace" launcher dock. See the module docstring
for the overall design and its known v1 simplifications."""
"""The desktop workbench window: an embedded IPython console dock plus
a "Namespace" launcher dock -- both movable/floatable/tabbable, same
as any opened device widget's dock (see _dock_widget_object). See the
module docstring for the overall design and its known v1
simplifications."""
def __init__(
self,
namespace=None,
theme="dark",
theme=None,
link_terminal=True,
auto_start=True,
scope="bernina",
@@ -615,6 +639,7 @@ class EcoDesktopApp:
# closing the window should also end the process.
self._owns_event_loop = False
self._console = None
self._console_dock = None
self._kernel_manager = None
self._kernel_client = None
self._kernel_session = None
@@ -662,7 +687,21 @@ class EcoDesktopApp:
if self.with_console:
self._build_console()
self.window.setCentralWidget(self._console)
# A QDockWidget, not the central widget -- so it's movable,
# floatable, and tabbable with the Namespace panel and any
# opened device widget, same as those. (No central widget is
# set at all in this branch: with none, QMainWindow gives the
# whole client area to the dock layout instead of carving out
# a fixed centre region for it, which is what lets the console
# dock end up filling that same space by default.)
dock = QtWidgets.QDockWidget("Console", self.window)
dock.setObjectName("console")
dock.setWidget(self._console)
dock.setFeatures(
QtWidgets.QDockWidget.DockWidgetMovable | QtWidgets.QDockWidget.DockWidgetFloatable
)
self.window.addDockWidget(QtCore.Qt.RightDockWidgetArea, dock)
self._console_dock = dock
else:
self.window.setCentralWidget(self._build_no_console_placeholder())
@@ -737,6 +776,69 @@ class EcoDesktopApp:
)
log_action.triggered.connect(self._open_log_viewer)
menu.addSeparator()
tabify_action = menu.addAction("Combine Panels into Tabs...")
tabify_action.setToolTip(
"Stack two or more open panels (Console, Namespace, or any open "
"device widget) together as tabs in one spot -- the same thing "
"dragging one panel's title bar onto another's does, just "
"without needing to land the drop exactly on the target's "
"title bar. Drag a tab off the tab bar afterwards to split it "
"back out."
)
tabify_action.triggered.connect(self._on_combine_into_tabs)
def _open_dock_panels(self):
"""name -> QDockWidget for every currently open, dockable panel
(Console, Namespace launcher, and each opened device widget) --
the candidates offered by "Combine Panels into Tabs..."."""
panels = {}
if self._console_dock is not None:
panels["Console"] = self._console_dock
if self._launcher_dock is not None:
panels["Namespace"] = self._launcher_dock
for dock in self._widget_docks:
panels[dock.windowTitle()] = dock
return panels
def _on_combine_into_tabs(self):
panels = self._open_dock_panels()
if len(panels) < 2:
QtWidgets.QMessageBox.information(
self.window,
"Combine Panels into Tabs",
"Need at least two open panels (Console, Namespace, or a device "
"widget) to combine.",
)
return
dialog = QtWidgets.QDialog(self.window)
dialog.setWindowTitle("Combine Panels into Tabs")
layout = QtWidgets.QVBoxLayout(dialog)
layout.addWidget(QtWidgets.QLabel("Select two or more panels to stack together as tabs:"))
checkboxes = {}
for name in panels:
checkbox = QtWidgets.QCheckBox(name)
layout.addWidget(checkbox)
checkboxes[name] = checkbox
buttons = QtWidgets.QDialogButtonBox(
QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel
)
buttons.accepted.connect(dialog.accept)
buttons.rejected.connect(dialog.reject)
layout.addWidget(buttons)
if dialog.exec_() != QtWidgets.QDialog.Accepted:
return
selected = [panels[name] for name, checkbox in checkboxes.items() if checkbox.isChecked()]
if len(selected) < 2:
return
first, *rest = selected
for dock in rest:
self.window.tabifyDockWidget(first, dock)
first.show()
first.raise_()
def _open_log_viewer(self):
"""eco.logs.widget(prefer="qt") -- see that module for what it
shows (kernel console history merged across sessions, on a
@@ -1226,7 +1328,7 @@ def _main(argv=None):
parser.add_argument(
"--theme",
choices=["dark", "light", "none"],
default="dark",
default="none",
help="modern skin, or 'none' for native OS style (default: %(default)s) "
"-- see eco.widgets.qt_theme",
)
+104
View File
@@ -0,0 +1,104 @@
"""Tests for CameraBasler/CameraPCO's .viewer() method and its
_default_widget = "viewer" wiring (eco.elements.assembly.Assembly.widget()'s
override mechanism -- see tests/test_assembly_default_widget.py for that
mechanism's own generic tests; these instead check that these two camera
classes plug into it correctly, resolving to the right cam_server pipeline
name for a real camera PV without the caller having to know/guess one).
Importing eco.devices_general.cameras_swissfel itself requires `cam_server`
(a hard, module-level import there) -- pytest.importorskip below mirrors
tests/test_camserver_stream_qt.py's own convention for that.
CameraBasler/CameraPCO.__init__ makes real cam_server/EPICS calls (camserver
alias registration, PV connections), so these tests call .viewer() as an
unbound method against a bare stand-in object carrying just the attributes
it actually reads (pvname) rather than constructing a real instance -- same
spirit as test_assembly_default_widget.py's FakeCameraLike.
"""
import pytest
pytest.importorskip("cam_server")
from eco.devices_general.cameras_swissfel import CameraBasler, CameraPCO
# the two real PVs this feature was built/verified against
BASLER_PVNAME = "SARES20-PROF141-M1" # eco.xdiagnostics.profile_monitors.ProfKbBernina's camera
PCO_PVNAME = "SARES20-PROF146-M1" # eco.xdiagnostics.profile_monitors.Pprm_dsd's camera
class _FakeCameraSelf:
def __init__(self, pvname):
self.pvname = pvname
def test_camera_basler_default_widget_is_viewer():
assert CameraBasler._default_widget == "viewer"
def test_camera_pco_default_widget_is_viewer():
assert CameraPCO._default_widget == "viewer"
def test_camera_basler_viewer_resolves_its_own_camera_pipeline(monkeypatch):
calls = {}
def fake_make_camserver_stream_qt(name, **kwargs):
calls["name"] = name
calls["kwargs"] = kwargs
return "the basler viewer"
monkeypatch.setattr(
"eco.widgets.camserver_stream_qt.make_camserver_stream_qt",
fake_make_camserver_stream_qt,
)
fake_self = _FakeCameraSelf(BASLER_PVNAME)
result = CameraBasler.viewer(fake_self)
assert result == "the basler viewer"
# the raw PV/camera name is passed through as-is, with kind=
# "camera_pipeline" doing the "{camera}_sp" resolution (and
# auto-creating that pipeline config if it doesn't exist yet) --
# see eco.widgets.camserver_stream_qt.resolve_camera_pipeline
assert calls["name"] == "SARES20-PROF141-M1"
assert calls["kwargs"]["kind"] == "camera_pipeline"
# cam=self: lets the viewer add its "Camera Settings" button (opens
# widget(normal=True) on the real camera Assembly, not a copy of it)
assert calls["kwargs"]["cam"] is fake_self
def test_camera_pco_viewer_resolves_its_own_camera_pipeline(monkeypatch):
calls = {}
def fake_make_camserver_stream_qt(name, **kwargs):
calls["name"] = name
calls["kwargs"] = kwargs
return "the pco viewer"
monkeypatch.setattr(
"eco.widgets.camserver_stream_qt.make_camserver_stream_qt",
fake_make_camserver_stream_qt,
)
fake_self = _FakeCameraSelf(PCO_PVNAME)
result = CameraPCO.viewer(fake_self)
assert result == "the pco viewer"
assert calls["name"] == "SARES20-PROF146-M1"
assert calls["kwargs"]["kind"] == "camera_pipeline"
assert calls["kwargs"]["cam"] is fake_self
def test_camera_basler_viewer_passes_through_rate_and_theme(monkeypatch):
calls = {}
monkeypatch.setattr(
"eco.widgets.camserver_stream_qt.make_camserver_stream_qt",
lambda name, **kwargs: calls.update(kwargs) or "viewer",
)
fake_self = _FakeCameraSelf(BASLER_PVNAME)
CameraBasler.viewer(fake_self, rate_hz=25.0, theme="dark", auto_start=False)
assert calls["rate_hz"] == 25.0
assert calls["theme"] == "dark"
assert calls["auto_start"] is False
+189
View File
@@ -4,13 +4,25 @@ import numpy as np
import pytest
pytest.importorskip("qtpy")
from qtpy import QtWidgets
from eco.widgets.camserver_stream_qt import (
CamServerStreamQt,
_StreamWorker,
default_pipeline_name,
normalize_to_uint8,
resolve_camera_pipeline,
resolve_stream,
)
# real PV/cam_server names this feature was built against: SARES20-PROF141-M1
# is the CameraBasler behind eco.xdiagnostics.profile_monitors.ProfKbBernina,
# SARES20-PROF146-M1 the CameraPCO behind
# eco.xdiagnostics.profile_monitors.Pprm_dsd (see tests/test_cameras_swissfel.py
# for the .viewer()-level tests using these same two names)
BASLER_CAMERA_NAME = "SARES20-PROF141-M1"
PCO_CAMERA_NAME = "SARES20-PROF146-M1"
def test_normalize_to_uint8_full_range():
arr = np.array([[0, 128], [255, 64]], dtype=np.uint16)
@@ -39,6 +51,131 @@ def test_normalize_to_uint8_rejects_non_2d():
normalize_to_uint8(np.zeros((2, 2, 3)))
def test_default_pipeline_name_matches_pshell_convention():
# ch.psi.pshell.screenpanel.CamServerViewer's default pipelineNameFormat
# ("%s_sp") decompiled from pshell-workbench -- see
# DEFAULT_PIPELINE_NAME_FORMAT's docstring
assert default_pipeline_name(BASLER_CAMERA_NAME) == "SARES20-PROF141-M1_sp"
assert default_pipeline_name(PCO_CAMERA_NAME) == "SARES20-PROF146-M1_sp"
def test_resolve_camera_pipeline_prefers_running_instance(monkeypatch):
cam_server = pytest.importorskip("cam_server")
class FakePipelineClient:
def __init__(self, url=None):
pass
def get_instance_stream(self, name):
assert name == "SARES20-PROF141-M1_sp"
return "tcp://example.psi.ch:9999"
def get_pipelines(self):
raise AssertionError("should not need to look at pipeline configs")
def create_instance_from_name(self, name):
raise AssertionError("should not create a new instance")
monkeypatch.setattr(cam_server, "PipelineClient", FakePipelineClient)
pipeline_name, address = resolve_camera_pipeline(BASLER_CAMERA_NAME)
assert pipeline_name == "SARES20-PROF141-M1_sp"
assert address == "tcp://example.psi.ch:9999"
def test_resolve_camera_pipeline_creates_config_when_missing(monkeypatch):
"""The piece pshell's screen panel has that plain resolve_stream(kind=
"pipeline") doesn't: not just reuse-or-create-an-instance-of-an-existing-
config, but first auto-create the pipeline *config* itself (with just
camera_name set) if even that doesn't exist yet."""
cam_server = pytest.importorskip("cam_server")
calls = []
class FakePipelineClient:
def __init__(self, url=None):
pass
def get_instance_stream(self, name):
raise RuntimeError("not running")
def get_pipelines(self):
return ["some_other_pipeline"]
def save_pipeline_config(self, name, config):
calls.append(("save", name, config))
def create_instance_from_name(self, name):
calls.append(("create", name))
return ("generated-id", "tcp://example.psi.ch:8888")
monkeypatch.setattr(cam_server, "PipelineClient", FakePipelineClient)
pipeline_name, address = resolve_camera_pipeline(PCO_CAMERA_NAME)
assert pipeline_name == "SARES20-PROF146-M1_sp"
assert address == "tcp://example.psi.ch:8888"
assert calls == [
("save", "SARES20-PROF146-M1_sp", {"camera_name": "SARES20-PROF146-M1"}),
("create", "SARES20-PROF146-M1_sp"),
]
def test_resolve_camera_pipeline_reuses_existing_config_without_resaving(monkeypatch):
cam_server = pytest.importorskip("cam_server")
calls = []
class FakePipelineClient:
def __init__(self, url=None):
pass
def get_instance_stream(self, name):
raise RuntimeError("not running")
def get_pipelines(self):
return ["SARES20-PROF141-M1_sp"]
def save_pipeline_config(self, name, config):
calls.append(("save", name, config))
def create_instance_from_name(self, name):
calls.append(("create", name))
return ("generated-id", "tcp://example.psi.ch:8888")
monkeypatch.setattr(cam_server, "PipelineClient", FakePipelineClient)
resolve_camera_pipeline(BASLER_CAMERA_NAME)
assert calls == [("create", "SARES20-PROF141-M1_sp")] # no "save" call
def test_resolve_camera_pipeline_create_false_reraises(monkeypatch):
cam_server = pytest.importorskip("cam_server")
class FakePipelineClient:
def __init__(self, url=None):
pass
def get_instance_stream(self, name):
raise RuntimeError("not running")
monkeypatch.setattr(cam_server, "PipelineClient", FakePipelineClient)
with pytest.raises(RuntimeError):
resolve_camera_pipeline(BASLER_CAMERA_NAME, create=False)
def test_resolve_stream_camera_pipeline_delegates(monkeypatch):
cam_server = pytest.importorskip("cam_server")
class FakePipelineClient:
def __init__(self, url=None):
pass
def get_instance_stream(self, name):
assert name == "SARES20-PROF146-M1_sp"
return "tcp://example.psi.ch:7777"
monkeypatch.setattr(cam_server, "PipelineClient", FakePipelineClient)
address = resolve_stream(PCO_CAMERA_NAME, kind="camera_pipeline")
assert address == "tcp://example.psi.ch:7777"
def test_resolve_stream_pipeline_prefers_running_instance(monkeypatch):
cam_server = pytest.importorskip("cam_server")
@@ -248,3 +385,55 @@ def test_stream_worker_pause_stops_new_frames(monkeypatch):
finally:
worker.stop()
worker.join(timeout=2)
# -- "Camera Settings" button (cam=) -----------------------------------------
# kind="demo" throughout: exercises the cam=/_open_settings wiring with real
# Qt widgets but with no cam_server/network dependency at all (the demo
# source needs neither).
class _FakeCamAssembly:
"""Stand-in for a CameraBasler/CameraPCO: only .widget(normal=...)
matters here -- see CameraBasler.viewer()/CamServerStreamQt._open_settings."""
def __init__(self):
self.widget_calls = []
def widget(self, normal=False):
self.widget_calls.append(normal)
return "the settings widget"
def _find_action(window, text):
matches = [a for a in window.findChildren(QtWidgets.QAction) if a.text() == text]
assert len(matches) == 1, f"expected exactly one {text!r} action, found {len(matches)}"
return matches[0]
def test_camera_settings_button_present_when_cam_given():
QtWidgets.QApplication.instance() or QtWidgets.QApplication([])
fake_cam = _FakeCamAssembly()
gui = CamServerStreamQt("demo", kind="demo", cam=fake_cam, auto_start=False)
try:
gui._build_window()
action = _find_action(gui.window, "Camera Settings")
action.trigger()
# normal=True: opens the plain property grid, not this same viewer
# again (CameraBasler/CameraPCO set _default_widget = "viewer") --
# mirrors AxisPTZStreamQt._open_settings
assert fake_cam.widget_calls == [True]
assert gui._settings_window == "the settings widget"
finally:
gui.stop()
def test_camera_settings_button_absent_without_cam():
QtWidgets.QApplication.instance() or QtWidgets.QApplication([])
gui = CamServerStreamQt("demo", kind="demo", auto_start=False)
try:
gui._build_window()
matches = [a for a in gui.window.findChildren(QtWidgets.QAction) if a.text() == "Camera Settings"]
assert matches == []
finally:
gui.stop()
+104 -7
View File
@@ -304,6 +304,37 @@ def test_init_all_click_initializes_everything_lazy_without_opening_any():
assert ns.init_all_calls == [{"required_only": False, "background": False}]
def test_init_all_reconciles_and_unblocks_each_entry_as_it_finishes():
"""Regression: previously every name in an Init All batch stayed in
self._loading -- spinner shown, unclickable via open_by_name's `name
in self._loading` guard -- until init_all() returned for the whole
batch, even though each entry actually finishes independently and
earlier. _refresh()'s reconciliation should drop a name out of
self._loading (and make it clickable/openable again) as soon as it's
no longer lazy, not only once the whole batch ends."""
app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([])
ns = _FakeNamespace(lazy=["a", "b", "c"], init_delay=0.1)
opened = []
launcher = _NamespaceLauncher(ns, on_open=opened.append)
launcher._on_init_all_clicked()
assert launcher._loading == {"a", "b", "c"}
# "a" finishes well before init_all() as a whole returns (which takes
# ~3 * 0.1s here) -- reconciliation should notice on its own, from the
# live-refresh/spinner tick, without waiting for the batch to end.
resolved = _pump(app, lambda: "a" not in launcher._loading, timeout=5.0)
assert resolved, "an entry that's already done should stop being tracked as loading"
assert "c" in launcher._loading # still mid-batch -- not everything is done yet
# and it's now actually clickable/openable, instead of being blocked
# by open_by_name's `name in self._loading` guard
launcher.open_by_name("a")
assert opened == ["a"]
assert _pump(app, lambda: not launcher._loading, timeout=5.0)
def test_init_all_click_with_nothing_lazy_is_a_no_op():
app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([])
ns = _FakeNamespace(initialized=["cam_west"])
@@ -1277,16 +1308,16 @@ def test_save_startup_script_returns_none_with_no_window():
# -- dark theme default ---------------------------------------------------
def test_desktop_app_defaults_to_dark_theme():
def test_desktop_app_defaults_to_native_theme():
import inspect
assert inspect.signature(EcoDesktopApp.__init__).parameters["theme"].default == "dark"
assert inspect.signature(EcoDesktopApp.__init__).parameters["theme"].default is None
def test_main_theme_defaults_to_dark(monkeypatch):
"""--theme's argparse default, and that 'none' maps back to Python
None (native style) -- see _main()'s `theme = None if args.theme ==
'none' else args.theme` translation."""
def test_main_theme_defaults_to_native(monkeypatch):
"""--theme's argparse default (native OS style), and that 'none' maps
back to Python None too -- see _main()'s `theme = None if args.theme
== 'none' else args.theme` translation."""
class _StubApp:
def run(self, workspace=None):
@@ -1301,10 +1332,76 @@ def test_main_theme_defaults_to_dark(monkeypatch):
monkeypatch.setattr(desktop_app, "EcoDesktopApp", fake_desktop_app)
monkeypatch.setattr(desktop_app, "build_namespace", lambda **kw: None)
desktop_app._main([])
assert captured["theme"] == "dark"
assert captured["theme"] is None
desktop_app._main(["--theme", "none"])
assert captured["theme"] is None
desktop_app._main(["--theme", "dark"])
assert captured["theme"] == "dark"
desktop_app._main(["--theme", "light"])
assert captured["theme"] == "light"
# -- console dock + "Combine Panels into Tabs..." --
def test_console_is_a_movable_floatable_dock_not_the_central_widget():
"""The console used to be window.setCentralWidget()'d, which a
QMainWindow never lets the user drag/float/tab -- it's now a
QDockWidget like the Namespace panel and any opened device widget,
so it can be rearranged the same way they can."""
app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([])
ns = _FakeNamespace(initialized=["prepump"])
gui = EcoDesktopApp(namespace=ns, auto_start=False)
gui._build_window()
try:
assert isinstance(gui._console_dock, QtWidgets.QDockWidget)
assert gui._console_dock.widget() is gui._console
assert gui._console_dock.features() & QtWidgets.QDockWidget.DockWidgetMovable
assert gui._console_dock.features() & QtWidgets.QDockWidget.DockWidgetFloatable
assert gui.window.centralWidget() is None
finally:
gui.stop()
def test_combine_into_tabs_requires_at_least_two_open_panels(monkeypatch):
informed = {}
monkeypatch.setattr(
QtWidgets.QMessageBox,
"information",
lambda *a, **k: informed.setdefault("shown", True),
)
app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([])
ns = _FakeNamespace(initialized=["prepump"])
gui = EcoDesktopApp(namespace=ns, with_console=False, auto_start=False)
gui._build_window()
try:
gui._on_combine_into_tabs()
assert informed.get("shown") is True
finally:
gui.stop()
def test_combine_into_tabs_tabifies_the_selected_panels(monkeypatch):
"""Simulates the dialog's checkboxes all being ticked and OK pressed
-- the resulting layout should have the Console and Namespace docks
tabified together, the same outcome as dragging one onto the other."""
def fake_exec(self):
for checkbox in self.findChildren(QtWidgets.QCheckBox):
checkbox.setChecked(True)
return QtWidgets.QDialog.Accepted
monkeypatch.setattr(QtWidgets.QDialog, "exec_", fake_exec)
app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([])
ns = _FakeNamespace(initialized=["prepump"])
gui = EcoDesktopApp(namespace=ns, auto_start=False)
gui._build_window()
try:
assert gui._launcher_dock not in gui.window.tabifiedDockWidgets(gui._console_dock)
gui._on_combine_into_tabs()
assert gui._launcher_dock in gui.window.tabifiedDockWidgets(gui._console_dock)
finally:
gui.stop()