more fixes

This commit is contained in:
lemke_h committed 2026-08-28 18:20:00 +02:00
1 parent d63bc10779
commit 6710fa1c85
10 files changed
+885 -177

No files matched your search

+9
View File
@@ -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) ---------------------------------------------------------
Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

+2 -1
View File
@@ -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
+46 -50
View File
@@ -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.
+14 -3
View File
@@ -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)
+150 -52
View File
@@ -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": "<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)
"p_target": 0.5, # optional, mbar (default P_TARGET)
"p_vent_target": 1000.0, # optional, mbar (default P_VENT_TARGET)
"lines": {
"<channel name>": {
"gauge": "<G PV>", # this channel's gauge
"valve_prevac": "<P PV>", # -> prevac/roots line
"valve_vent": "<V PV>", # -> 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},
+57 -30
View File
@@ -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:
+154 -40
View File
@@ -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>{%title%}</title>
{%favicon%}
{%css%}
<style>
/* Without this reset, the default body margin plus the
<object>'s inline-replaced-element baseline gap (the same
few extra px an <img>/<object> sized to 100% always
leaves below itself unless it's display:block -- a classic,
easy-to-miss source of an unwanted scrollbar) push the
page's total size just past the viewport, so a scrollbar
appears even though nothing meaningful is actually
scrollable. */
html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; background: #f0f0f0; }
</style>
</head>
<body>
{%app_entry%}
@@ -203,30 +272,38 @@ def _run_dash_server(svg_path, ip_instance, namespace_prefix=None, exclude_group
<script>
__EXTRACT_COMMAND_JS__
// Script tracking click events inside the SVG's internal document DOM tree
function attachSvgClickHandler(svgDoc) {
svgDoc.addEventListener("click", function(e) {
let target = e.target;
while (target && target !== svgDoc) {
let commandStr = extractCommand(target);
// Script tracking click events inside the SVG's internal document DOM tree.
// A stable, named function (not a fresh closure per call) so that
// re-attaching it (see the live-refresh block below, which does
// so defensively after every refresh) is a safe no-op if it's
// already attached -- addEventListener only dedupes when given
// the exact same function reference twice.
function svgClickHandler(e) {
let svgDoc = e.currentTarget;
let target = e.target;
while (target && target !== svgDoc) {
let commandStr = extractCommand(target);
if (commandStr) {
var relay = document.getElementById("click-relay");
if (relay) {
// React tracks <input> values through its own setter, so
// assigning relay.value directly and dispatching "input"
// is invisible to it - go through the native setter instead.
var nativeSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
nativeSetter.call(relay, commandStr + "|||" + e.ctrlKey + "|||" + Math.random());
var event = new Event("input", { bubbles: true });
relay.dispatchEvent(event);
}
e.preventDefault();
break;
if (commandStr) {
var relay = document.getElementById("click-relay");
if (relay) {
// React tracks <input> values through its own setter, so
// assigning relay.value directly and dispatching "input"
// is invisible to it - go through the native setter instead.
var nativeSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
nativeSetter.call(relay, commandStr + "|||" + e.ctrlKey + "|||" + Math.random());
var event = new Event("input", { bubbles: true });
relay.dispatchEvent(event);
}
target = target.parentNode;
e.preventDefault();
break;
}
});
target = target.parentNode;
}
}
function attachSvgClickHandler(svgDoc) {
svgDoc.addEventListener("click", svgClickHandler);
}
function setupSvgListener() {
@@ -252,23 +329,41 @@ def _run_dash_server(svg_path, ip_instance, namespace_prefix=None, exclude_group
// Live panel only (__LIVE_REFRESH_INTERVAL_MS__ is 0
// otherwise, so this is a no-op setInterval that never
// fires): periodically reload the embedded SVG object from
// /svg-content, which re-runs `refresh()` server-side on
// every hit -- see _run_dash_server's docstring. Resetting
// .data forces the browser to actually re-fetch (a cache-
// busting query param, since GET responses could otherwise
// be cached) rather than reuse the existing embedded
// document; clearing listenerAttached first lets
// setupSvgListener() re-attach the click handler to the new
// document once it's ready.
// fires): periodically re-fetch /svg-content (re-running
// `refresh()` server-side on every hit -- see
// _run_dash_server's docstring) and patch it into the
// *already-open* embedded document in place, instead of
// resetting the <object>'s `.data` to force a full reload.
// A full reload is what the first version of this did, and
// it visibly blinks/flashes on every tick (the embedded
// document briefly unloads) -- distracting and not really
// usable at a useful refresh rate. An in-place DOM patch
// (same technique the old Qt-only refresh path used:
// replacing the live `<svg>` root, not reloading the page
// around it) doesn't reload anything, so there's nothing to
// flash. The click listener is registered on `svgDoc` itself
// (attachSvgClickHandler), not the specific <svg> node being
// replaced, so it should keep working across the swap on its
// own -- but it's re-attached after every tick anyway
// (harmless now that it's a stable function reference, see
// svgClickHandler above) as a defensive belt-and-braces
// measure, in case some engine-specific quirk of replacing a
// same-origin embedded document's root element ever detaches
// document-level listeners.
var LIVE_REFRESH_INTERVAL_MS = __LIVE_REFRESH_INTERVAL_MS__;
if (LIVE_REFRESH_INTERVAL_MS > 0) {
setInterval(function() {
var embedObj = document.getElementById("inkscape-svg-object");
if (!embedObj) return;
embedObj.dataset.listenerAttached = "";
embedObj.data = "/svg-content?t=" + Date.now();
setupSvgListener();
var svgDoc = embedObj ? embedObj.contentDocument : null;
if (!svgDoc || !svgDoc.documentElement) return;
fetch("/svg-content?t=" + Date.now())
.then(function(r) { return r.text(); })
.then(function(newSvgText) {
var newRoot = new DOMParser().parseFromString(newSvgText, "image/svg+xml").documentElement;
svgDoc.replaceChild(svgDoc.importNode(newRoot, true), svgDoc.documentElement);
attachSvgClickHandler(svgDoc);
})
.catch(function(err) { console.error("eco SVG live refresh failed:", err); });
}, LIVE_REFRESH_INTERVAL_MS);
}
</script>
@@ -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
# <style> above) rather than 100vw/95vh: vw/vh measure the *viewport*,
# which on a page that actually has a scrollbar excludes the
# scrollbar's own width, so 100vw ends up wider than the space really
# available and helps trigger exactly the scrollbar it's supposed to
# fit inside. display:block clears the few extra px of inline-
# replaced-element baseline gap <object>/<img>-like elements get by
# default, the other classic contributor to an unwanted scrollbar
# here.
html.ObjectEl(
id="inkscape-svg-object",
data="/svg-content",
type="image/svg+xml",
style={"width": "100vw", "height": "95vh", "border": "none"}
style={"width": "100%", "height": "100%", "display": "block", "border": "none"}
),
# Standard input field used as a bridge channel between JS events and Python callbacks
dcc.Input(id="click-relay", type="text", style={"display": "none"})
], style={"margin": "0", "padding": "0", "backgroundColor": "#f0f0f0"})
], style={"margin": "0", "padding": "0", "width": "100%", "height": "100%", "backgroundColor": "#f0f0f0"})
@app.callback(
Output("click-relay", "style"),
@@ -316,8 +420,8 @@ def _run_dash_server(svg_path, ip_instance, namespace_prefix=None, exclude_group
print(f"\n[SVG Paste] -> {command_str}", end="", flush=True)
ip_instance.set_next_input(command_str, replace=False)
else:
print(f"\nExecuting from SVG: {command_str}")
ip_instance.run_cell(command_str)
# Never run it inline here -- see _dispatch_command.
_dispatch_command(ip_instance, command_str)
except Exception as err:
print(f"\nError processing event layout channel: {err}")
@@ -340,7 +444,17 @@ def _run_dash_server(svg_path, ip_instance, namespace_prefix=None, exclude_group
# polling EPICS forever in the background for the rest of the session.
from werkzeug.serving import make_server
server = make_server("127.0.0.1", 0, app.server)
# threaded=True is ESSENTIAL, not a tuning knob: make_server defaults to
# threaded=False, i.e. one request at a time. `app.run()` (what this
# replaced) defaults to threaded=True, so switching to make_server for
# the port=0 support silently made this server serial -- and a serial
# server breaks a live panel completely the moment anything slow runs:
# one in-flight request blocks every subsequent /svg-content refresh AND
# every subsequent click, so the panel freezes after the first click and
# never recovers. (Clicked commands are additionally dispatched off the
# request thread entirely, see _dispatch_command, so even a 5-minute
# pump_down() doesn't tie up a request thread at all.)
server = make_server("127.0.0.1", 0, app.server, threaded=True)
if port_holder is not None:
port_holder["port"] = server.server_port
port_holder["server"] = server
+440
View File
@@ -0,0 +1,440 @@
"""
Simple, stock-Qt counterparts of eco.widgets.indicator_widgets_ipy's
first-pass ipywidgets gadgets -- built entirely from plain QWidgets
(QProgressBar, QSlider, QPushButton, QLabel, a row of checkable
QPushButtons for the enum "dial") rather than eco.widgets.indicator_widgets'
hand-painted QPainter gauges/dial face. This is the Qt-side half of a
matched, as-simple-as-possible pair with indicator_widgets_ipy -- see
docs/widget_views.md, which documents both side by side. The richer,
hand-drawn eco.widgets.indicator_widgets gadgets (real needle gauge, radial
enum dial, live strip-chart) are unaffected and remain available; this
module is a deliberately lower-effort alternative, not a replacement.
Same function names/signatures/kind strings as
eco.widgets.indicator_widgets_ipy, so the two are interchangeable at a
call site modulo which backend is running -- see
eco.widgets.containers/eco.utilities.utilities.is_notebook for the
existing convention of picking a backend automatically.
Each function builds one live, self-polling QWidget (own background
thread + Qt signal bridge to marshal each reading onto the GUI thread,
own .stop()) for one Adjustable/Detector item -- same
threading-plus-signal-bridge pattern eco.widgets.display_qt and
eco.widgets.indicator_widgets already use (unlike ipywidgets, touching a
QWidget from a non-GUI thread is not safe, so this can't just set
`.value` directly the way indicator_widgets_ipy does). Writes go through
item.set_target_value() on a short-lived thread, same convention
throughout eco's widgets.
Usage:
from eco.widgets.indicator_widgets_qt_simple import bar_gauge
gauge = bar_gauge(my_assembly.pressure, vmin=0, vmax=100)
gauge.show()
"""
import enum
import threading
from qtpy import QtCore, QtWidgets
def _format_value(value):
if isinstance(value, enum.Enum):
return value.name
try:
return f"{float(value):.4g}"
except (TypeError, ValueError):
return str(value)
def _guess_range(item):
"""Best-effort (vmin, vmax) -- same heuristic as
eco.widgets.indicator_widgets._guess_range/
eco.widgets.indicator_widgets_ipy._guess_range (duplicated rather than
imported, same reasoning as the ipywidgets module: keeping each
backend's module self-contained)."""
for lo_attr, hi_attr in (("low_limit", "high_limit"), ("llm", "hlm"), ("lolim", "hilim")):
try:
lo, hi = getattr(item, lo_attr, None), getattr(item, hi_attr, None)
if lo is not None and hi is not None and float(hi) > float(lo):
return float(lo), float(hi)
except Exception:
pass
try:
limits = getattr(item, "limits", None)
if limits and len(limits) == 2 and float(limits[1]) > float(limits[0]):
return float(limits[0]), float(limits[1])
except Exception:
pass
return 0.0, 100.0
def _enum_index(value, enum_strs):
"""Best-effort index of `value` within `enum_strs` -- see
eco.widgets.indicator_widgets_ipy._enum_index, identical logic."""
if isinstance(value, enum.Enum):
value = value.name
if isinstance(value, str):
try:
return enum_strs.index(value)
except ValueError:
return None
try:
idx = int(value)
except (TypeError, ValueError):
return None
return idx if 0 <= idx < len(enum_strs) else None
def _item_name(item, title):
if title is not None:
return title
alias = getattr(item, "alias", None)
get_full_name = getattr(alias, "get_full_name", None)
if callable(get_full_name):
try:
name = get_full_name()
if name:
return name
except Exception:
pass
return getattr(item, "name", None) or str(item)
class _PollBridge(QtCore.QObject):
updated = QtCore.Signal(object)
def _start_poll(widget, get_value, render, poll_interval, stop_event):
"""Background thread: read get_value() every poll_interval seconds and
marshal each reading to render(value) on the GUI thread via a Qt
signal. The bridge is stashed on `widget` so it survives as long as
the widget does -- a local-only QObject with a connected signal can
otherwise be garbage-collected out from under the connection."""
bridge = _PollBridge()
bridge.updated.connect(render)
widget._bridge = bridge
def _loop():
while not stop_event.is_set():
try:
value = get_value()
except Exception:
pass
else:
bridge.updated.emit(value)
if stop_event.wait(poll_interval):
break
thread = threading.Thread(target=_loop, daemon=True)
thread.start()
return thread
def led_indicator(item, title=None, on_value=True, off_value=False, threshold=None, poll_interval=0.3):
"""A round on/off indicator: a plain QPushButton painted green/red/gray
via its stylesheet. "On" means value == on_value, or, if `threshold`
is given, value >= threshold. Click to toggle if the item is
settable."""
name = _item_name(item, title)
settable = hasattr(item, "set_target_value")
state = {"is_on": None}
btn = QtWidgets.QPushButton()
btn.setFixedSize(28, 28)
btn.setEnabled(settable)
btn.setToolTip(str(name))
def _paint(is_on):
color = "#9aa0a6" if is_on is None else ("#2ecc71" if is_on else "#e74c3c")
btn.setStyleSheet(
f"background-color: {color}; border-radius: 14px; border: 2px solid #2c2c2c;"
)
def _render(value):
if threshold is not None:
try:
is_on = float(value) >= threshold
except (TypeError, ValueError):
is_on = None
else:
is_on = value == on_value
state["is_on"] = is_on
_paint(is_on)
def _on_click():
if not settable:
return
new_value = off_value if state["is_on"] else on_value
threading.Thread(target=lambda: item.set_target_value(new_value), daemon=True).start()
btn.clicked.connect(_on_click)
_paint(None)
box = QtWidgets.QWidget()
lay = QtWidgets.QHBoxLayout(box)
lay.setContentsMargins(4, 4, 4, 4)
lay.addWidget(QtWidgets.QLabel(str(name)))
lay.addWidget(btn)
stop_event = threading.Event()
_start_poll(box, item.get_current_value, _render, poll_interval, stop_event)
box.stop = stop_event.set
return box
def bar_gauge(item, title=None, vmin=None, vmax=None, orientation="vertical", poll_interval=0.5):
"""A vertical (default) or horizontal fill bar against [vmin, vmax] --
stock QProgressBar, read-only (use slider() for a settable bar-like
control)."""
name = _item_name(item, title)
if vmin is None or vmax is None:
vmin, vmax = _guess_range(item)
bar = QtWidgets.QProgressBar()
bar.setOrientation(QtCore.Qt.Vertical if orientation == "vertical" else QtCore.Qt.Horizontal)
bar.setRange(0, 1000)
if orientation == "vertical":
bar.setMinimumSize(28, 120)
else:
bar.setMinimumSize(160, 24)
def _render(value):
try:
v = float(value)
except (TypeError, ValueError):
bar.setFormat(_format_value(value))
return
span = vmax - vmin
frac = 0.0 if span == 0 else (v - vmin) / span
bar.setValue(int(round(max(0.0, min(1.0, frac)) * 1000)))
bar.setFormat(_format_value(v))
box = QtWidgets.QWidget()
lay = QtWidgets.QVBoxLayout(box) if orientation == "vertical" else QtWidgets.QHBoxLayout(box)
lay.setContentsMargins(4, 4, 4, 4)
label = QtWidgets.QLabel(str(name))
label.setAlignment(QtCore.Qt.AlignCenter)
lay.addWidget(label)
lay.addWidget(bar)
stop_event = threading.Event()
_start_poll(box, item.get_current_value, _render, poll_interval, stop_event)
box.stop = stop_event.set
return box
def analog_gauge(item, title=None, vmin=None, vmax=None, poll_interval=0.5):
"""Stock-Qt stand-in for indicator_widgets.AnalogGauge's semicircular
needle look: the same live horizontal bar_gauge, not a needle. See
eco.widgets.indicator_widgets for the richer, hand-painted version."""
return bar_gauge(item, title=title, vmin=vmin, vmax=vmax, orientation="horizontal", poll_interval=poll_interval)
def strip_chart(item, title=None, poll_interval=0.3, window_points=100):
"""Stock-Qt stand-in for indicator_widgets.StripChart's rolling line
plot: no line, just the current value plus a bar showing where it
falls within the min/max seen so far. `window_points` is accepted
for interface parity but unused (there is no history buffer to cap).
Mirrors eco.widgets.indicator_widgets_ipy.strip_chart exactly."""
name = _item_name(item, title)
seen = {"lo": None, "hi": None}
bar = QtWidgets.QProgressBar()
bar.setRange(0, 1000)
bar.setMinimumSize(160, 24)
bar.setTextVisible(False)
value_label = QtWidgets.QLabel("--")
def _render(value):
try:
v = float(value)
except (TypeError, ValueError):
value_label.setText(_format_value(value))
return
lo = v if seen["lo"] is None else min(seen["lo"], v)
hi = v if seen["hi"] is None else max(seen["hi"], v)
seen["lo"], seen["hi"] = lo, hi
span = hi - lo
frac = 0.5 if span == 0 else (v - lo) / span
bar.setValue(int(round(max(0.0, min(1.0, frac)) * 1000)))
value_label.setText(f"{_format_value(v)} [{_format_value(lo)} .. {_format_value(hi)}]")
box = QtWidgets.QWidget()
lay = QtWidgets.QVBoxLayout(box)
lay.setContentsMargins(4, 4, 4, 4)
lay.addWidget(QtWidgets.QLabel(str(name)))
lay.addWidget(bar)
lay.addWidget(value_label)
stop_event = threading.Event()
_start_poll(box, item.get_current_value, _render, poll_interval, stop_event)
box.stop = stop_event.set
return box
def numeric_tile(item, title=None, poll_interval=0.5, fmt="{:.4g}"):
"""A compact "KPI tile": name plus a large numeric readout -- stock
QLabel with an enlarged font, no sparkline (see strip_chart's
docstring for why; same reasoning applies here)."""
name = _item_name(item, title)
label = QtWidgets.QLabel(str(name))
number = QtWidgets.QLabel("--")
number.setAlignment(QtCore.Qt.AlignCenter)
font = number.font()
font.setPointSize(font.pointSize() + 10)
font.setBold(True)
number.setFont(font)
def _render(value):
try:
text = fmt.format(value)
except Exception:
text = _format_value(value)
number.setText(text)
box = QtWidgets.QWidget()
lay = QtWidgets.QVBoxLayout(box)
lay.setContentsMargins(4, 4, 4, 4)
lay.addWidget(label)
lay.addWidget(number)
stop_event = threading.Event()
_start_poll(box, item.get_current_value, _render, poll_interval, stop_event)
box.stop = stop_event.set
return box
def slider(item, title=None, vmin=None, vmax=None, step=None, poll_interval=0.5):
"""A horizontal slider over [vmin, vmax] with a numeric readout --
stock QSlider. Interactive (writes via set_target_value on release)
if the item is settable; otherwise disabled, just following the
polled value."""
name = _item_name(item, title)
if vmin is None or vmax is None:
vmin, vmax = _guess_range(item)
settable = hasattr(item, "set_target_value")
step = step or max((vmax - vmin) / 200.0, 1e-9)
sl = QtWidgets.QSlider(QtCore.Qt.Horizontal)
n_steps = max(1, int(round((vmax - vmin) / step)))
sl.setRange(0, n_steps)
sl.setEnabled(settable)
sl.setMinimumWidth(200)
value_label = QtWidgets.QLabel("--")
value_label.setFixedWidth(60)
def _pos_to_value(pos):
return vmin + pos * step
def _value_to_pos(value):
return int(round((value - vmin) / step))
def _render(value):
try:
v = float(value)
except (TypeError, ValueError):
return
value_label.setText(_format_value(v))
if sl.isSliderDown():
return
sl.blockSignals(True)
sl.setValue(max(sl.minimum(), min(sl.maximum(), _value_to_pos(v))))
sl.blockSignals(False)
def _on_release():
new_value = _pos_to_value(sl.value())
threading.Thread(target=lambda: item.set_target_value(new_value), daemon=True).start()
if settable:
sl.sliderReleased.connect(_on_release)
box = QtWidgets.QWidget()
lay = QtWidgets.QHBoxLayout(box)
lay.setContentsMargins(4, 4, 4, 4)
lay.addWidget(QtWidgets.QLabel(str(name)))
lay.addWidget(sl, 1)
lay.addWidget(value_label)
stop_event = threading.Event()
_start_poll(box, item.get_current_value, _render, poll_interval, stop_event)
box.stop = stop_event.set
return box
def dial(item, title=None, vmin=None, vmax=None, step=None, poll_interval=0.5):
"""Stock-Qt stand-in for indicator_widgets.Dial. For an enum-valued
item (anything exposing `enum_strs`), a row of checkable
QPushButtons showing every choice at once -- same idea as
indicator_widgets_ipy.dial's ToggleButtons, not the radial
mode-select ring the richer Qt Dial draws. For a plain numeric item,
the same QSlider as slider()."""
enum_strs = list(getattr(item, "enum_strs", None) or [])
if not enum_strs:
return slider(item, title=title, vmin=vmin, vmax=vmax, step=step, poll_interval=poll_interval)
name = _item_name(item, title)
settable = hasattr(item, "set_target_value")
suppress = [False]
buttons = []
def _on_clicked(idx):
if suppress[0] or not settable:
return
new_value = enum_strs[idx]
threading.Thread(target=lambda: item.set_target_value(new_value), daemon=True).start()
btn_row = QtWidgets.QHBoxLayout()
for i, choice_label in enumerate(enum_strs):
b = QtWidgets.QPushButton(choice_label)
b.setCheckable(True)
b.setEnabled(settable)
b.clicked.connect(lambda checked=False, i=i: _on_clicked(i))
btn_row.addWidget(b)
buttons.append(b)
def _render(value):
idx = _enum_index(value, enum_strs)
if idx is None:
return
suppress[0] = True
try:
for i, b in enumerate(buttons):
b.setChecked(i == idx)
finally:
suppress[0] = False
box = QtWidgets.QWidget()
lay = QtWidgets.QVBoxLayout(box)
lay.setContentsMargins(4, 4, 4, 4)
lay.addWidget(QtWidgets.QLabel(str(name)))
lay.addLayout(btn_row)
stop_event = threading.Event()
_start_poll(box, item.get_current_value, _render, poll_interval, stop_event)
box.stop = stop_event.set
return box
#: same kind strings as eco.widgets.indicator_widgets.INDICATOR_TYPES /
#: eco.widgets.indicator_widgets_ipy.INDICATOR_TYPES -> (builder, needs_range)
INDICATOR_TYPES = (
("LED", led_indicator, False),
("Bar gauge", bar_gauge, True),
("Analog gauge", analog_gauge, True),
("Strip chart", strip_chart, False),
("Numeric tile (KPI)", numeric_tile, False),
("Dial / knob", dial, True),
("Slider", slider, True),
)
def create_indicator(kind, item, title=None, vmin=None, vmax=None, **kwargs):
"""Build one indicator gadget by name (one of INDICATOR_TYPES' first
elements, e.g. "LED"/"Bar gauge"/...) -- same kind strings as the
other two indicator-widget modules' create_indicator."""
for label, factory, needs_range in INDICATOR_TYPES:
if label == kind:
if needs_range:
return factory(item, title=title, vmin=vmin, vmax=vmax, **kwargs)
return factory(item, title=title, **kwargs)
raise ValueError(f"unknown indicator kind {kind!r}; choose one of {[t[0] for t in INDICATOR_TYPES]}")
+13 -1
View File
@@ -79,4 +79,16 @@ term.set_title()
from IPython import get_ipython
_ipy = get_ipython()
_ipy.Completer.use_jedi = True
# Must stay False, and must match eco/startup_inline.py (which has the long
# form of this comment) -- this file had drifted to True, which silently
# breaks tab completion in exactly the session the facility launcher
# `/sf/bernina/bin/eco` starts (it runs startup_inline_new.py -> this file).
# Jedi doesn't just make completion slow on eco's dynamic namespace/Assembly
# objects, it returns *nothing*: measured on an initialized `prepump`,
# use_jedi=True gave 0 matches where the classic completer gave 33 (the
# 5.8s vs 0.001s / 0-vs-63 figures in eco/startup_inline.py are the same
# effect on a bigger object). The classic completer goes through `dir()`,
# which eco's lazy Proxy.__dir__ answers correctly -- staying "shy" while
# a component is still unresolved (so completing a shared prefix doesn't
# initialize every sibling) and forwarding to the real object once it is.
_ipy.Completer.use_jedi = False