Web front-end (PWA) prototype: eco/web, not wired into eco yet
A fourth front-end next to shell, desktop and lab/voila: one gateway process in the session (tornado, own thread, 127.0.0.1 + token), many thin browser clients. Values via live_values.LiveReader and writes via start_write, as in the Qt and ipywidgets grids; writes off by default. Namespace list with lazy init, device grid, SVG panels, reconnect, installable as an app. Nothing imports eco.web; start it with eco.web.start_web() or try it with python -m eco.web --demo. Plan, protocol and status in web_frontend/.
This commit is contained in:
1 parent
e670f6a806
commit
a82b38d725
21 files changed
+2901
No files matched your search
@@ -0,0 +1,63 @@
|
||||
"""eco's web front-end (PWA) -- in development, not wired into eco yet.
|
||||
|
||||
Nothing in eco imports this package; it is started explicitly::
|
||||
|
||||
from eco.web import start_web
|
||||
gw = start_web() # this session's `namespace`, read-only
|
||||
gw = start_web(writes=True) # allow writes from the browser
|
||||
stop_web()
|
||||
|
||||
or, without any beamline, against a simulated namespace::
|
||||
|
||||
python -m eco.web --demo
|
||||
|
||||
It prints a URL with an access token, for ``http://localhost:<port>``. From
|
||||
elsewhere, forward the port over SSH first (``ssh -L 8097:localhost:8097
|
||||
<host>``). Plan, protocol and status: ``web_frontend/`` at the repo root.
|
||||
"""
|
||||
from eco.web.gateway import DEFAULT_PORT
|
||||
|
||||
_gateway = None
|
||||
|
||||
|
||||
def start_web(namespace=None, port=DEFAULT_PORT, writes=False, host="127.0.0.1",
|
||||
token=None, poll_interval=1.0, quiet=False):
|
||||
"""Serve `namespace` (default: the calling session's `namespace`) to
|
||||
the web client. Returns the running gateway (``.url``, ``.stop()``).
|
||||
One per session: calling it again returns the running one."""
|
||||
global _gateway
|
||||
from eco.web.backends import SessionBackend, calling_namespace
|
||||
from eco.web.gateway import WebGateway
|
||||
|
||||
if _gateway is not None and _gateway.running:
|
||||
if not quiet:
|
||||
print(f"eco web already running: {_gateway.url}")
|
||||
return _gateway
|
||||
if namespace is None:
|
||||
namespace = calling_namespace()
|
||||
if namespace is None:
|
||||
raise RuntimeError("no namespace given and none found in this session")
|
||||
_gateway = WebGateway(SessionBackend(namespace), host=host, port=port, token=token,
|
||||
writes=writes, poll_interval=poll_interval).start()
|
||||
if not quiet:
|
||||
print(connection_help(_gateway))
|
||||
return _gateway
|
||||
|
||||
|
||||
def stop_web():
|
||||
global _gateway
|
||||
if _gateway is not None:
|
||||
_gateway.stop()
|
||||
_gateway = None
|
||||
|
||||
|
||||
def connection_help(gateway):
|
||||
import socket
|
||||
|
||||
mode = "writes ENABLED" if gateway.writes else "read-only"
|
||||
return (
|
||||
f"eco web ({mode}) on this host, port {gateway.port}:\n"
|
||||
f" {gateway.url}\n"
|
||||
f"from another machine, forward the port first:\n"
|
||||
f" ssh -L {gateway.port}:localhost:{gateway.port} {socket.gethostname()}"
|
||||
)
|
||||
@@ -0,0 +1,39 @@
|
||||
"""python -m eco.web --demo [--writes] [--port N]
|
||||
|
||||
Serves the simulated namespace of eco.web.demo, for developing the web
|
||||
client anywhere. A real session uses eco.web.start_web() instead.
|
||||
"""
|
||||
import argparse
|
||||
import time
|
||||
|
||||
from eco.web import connection_help
|
||||
from eco.web.gateway import DEFAULT_PORT
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(prog="python -m eco.web", description=__doc__.split("\n\n")[0])
|
||||
parser.add_argument("--demo", action="store_true", help="serve the simulated namespace (required for now)")
|
||||
parser.add_argument("--writes", action="store_true", help="allow writes from the browser")
|
||||
parser.add_argument("--port", type=int, default=DEFAULT_PORT)
|
||||
parser.add_argument("--host", default="127.0.0.1")
|
||||
parser.add_argument("--token", default=None, help="fixed token; \"random\" for a new one; default: ~/.eco/web_token")
|
||||
args = parser.parse_args(argv)
|
||||
if not args.demo:
|
||||
parser.error("only --demo is supported from the command line; in a session use eco.web.start_web()")
|
||||
|
||||
from eco.web.backends import SessionBackend
|
||||
from eco.web.demo import DemoNamespace
|
||||
from eco.web.gateway import WebGateway
|
||||
|
||||
gateway = WebGateway(SessionBackend(DemoNamespace()), host=args.host, port=args.port,
|
||||
token=args.token, writes=args.writes).start()
|
||||
print(connection_help(gateway))
|
||||
try:
|
||||
while True:
|
||||
time.sleep(3600)
|
||||
except KeyboardInterrupt:
|
||||
gateway.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Where the gateway gets its objects from.
|
||||
|
||||
`SessionBackend` wraps a live eco session's namespace (hosting mode B in
|
||||
web_frontend/ARCHITECTURE.md). A status-server backend (mode A, read-only)
|
||||
is meant to implement the same small interface later:
|
||||
|
||||
- ``label`` -- shown in the client's title bar
|
||||
- ``names()`` -- {"initialized": [...], "lazy": [...], "failed": {name: reason}}
|
||||
- ``resolve(name)`` -- a top-level object, initializing a lazy one
|
||||
- ``svg(obj, live)`` -- (svg text, click prefix) for an object with a panel
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
|
||||
from eco.web.viewmodels import full_name
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
MAX_REASON = 400
|
||||
|
||||
|
||||
class NotFound(LookupError):
|
||||
pass
|
||||
|
||||
|
||||
def attach_ca_context():
|
||||
"""Attach this worker thread to the process's one CA context before it
|
||||
makes CA calls -- a second, implicitly created context in the same
|
||||
process is a documented segfault source (see the long comment in
|
||||
eco.widgets.desktop_app._NamespaceLauncher's init thread)."""
|
||||
try:
|
||||
import epics.ca as ca
|
||||
|
||||
ca.use_initial_context()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
class SessionBackend:
|
||||
def __init__(self, namespace, label=None):
|
||||
self.namespace = namespace
|
||||
self.label = label or getattr(namespace, "name", None) or "eco"
|
||||
self._init_lock = threading.Lock()
|
||||
|
||||
def names(self):
|
||||
ns = self.namespace
|
||||
reasons = getattr(ns, "failed_items_excpetion", {}) or {}
|
||||
failed = {}
|
||||
for name in sorted(getattr(ns, "failed_names", set())):
|
||||
reason = reasons.get(name)
|
||||
failed[name] = (f"{type(reason).__name__}: {reason}" if reason is not None else "")[:MAX_REASON]
|
||||
return {
|
||||
"initialized": sorted(getattr(ns, "initialized_names", set())),
|
||||
"lazy": sorted(getattr(ns, "lazy_names", set())),
|
||||
"failed": failed,
|
||||
}
|
||||
|
||||
def resolve(self, name):
|
||||
"""A top-level component (initialized first if lazy), or a dotted
|
||||
attribute path below one ("mono.energy"); private parts refused."""
|
||||
ns = self.namespace
|
||||
if name not in getattr(ns, "all_names", set()) and "." in name:
|
||||
head, *parts = name.split(".")
|
||||
if any(not part or part.startswith("_") for part in parts):
|
||||
raise NotFound(f"not a public name: {name!r}")
|
||||
obj = self.resolve(head)
|
||||
for part in parts:
|
||||
try:
|
||||
obj = getattr(obj, part)
|
||||
except AttributeError:
|
||||
raise NotFound(f"no {part!r} in {name!r}") from None
|
||||
return obj
|
||||
if name not in getattr(ns, "all_names", set()):
|
||||
raise NotFound(f"no component {name!r} in {self.label}")
|
||||
if name in getattr(ns, "lazy_names", set()):
|
||||
attach_ca_context()
|
||||
with self._init_lock: # one at a time, like the desktop launcher's clicks
|
||||
if name in ns.lazy_names:
|
||||
ns.init_name(name, raise_errors=False, verbose=False)
|
||||
if name in getattr(ns, "failed_names", set()):
|
||||
raise NotFound(f"{name} failed to initialize: {self.names()['failed'].get(name, '')}")
|
||||
obj = ns.resolve_item(name)
|
||||
from eco.utilities.config import Proxy
|
||||
|
||||
if isinstance(obj, Proxy):
|
||||
obj = obj.__wrapped__
|
||||
return obj
|
||||
|
||||
def svg(self, obj, live=True):
|
||||
"""The SVG panel of `obj` as text, plus the prefix its click markers
|
||||
are relative to (Assembly.show: commands run against the assembly's
|
||||
own full name)."""
|
||||
attach_ca_context()
|
||||
path = None
|
||||
if callable(getattr(type(obj), "_widget_svg_panel", None)):
|
||||
path = obj._widget_svg_panel(live=live)
|
||||
if not path:
|
||||
path = object.__getattribute__(obj, "__dict__").get("_show_svg")
|
||||
if not path or not os.path.exists(path):
|
||||
raise NotFound(f"{full_name(obj)} has no SVG panel")
|
||||
with open(path, encoding="utf-8") as f:
|
||||
return f.read(), full_name(obj)
|
||||
|
||||
|
||||
def calling_namespace():
|
||||
"""The `namespace` variable of the running IPython session, as
|
||||
eco.widgets.app_launchers does for the desktop."""
|
||||
try:
|
||||
from IPython import get_ipython
|
||||
|
||||
ip = get_ipython()
|
||||
except Exception:
|
||||
ip = None
|
||||
if ip is None:
|
||||
return None
|
||||
return getattr(ip, "user_ns", {}).get("namespace")
|
||||
@@ -0,0 +1,266 @@
|
||||
"""One connected client: the protocol of web_frontend/PROTOCOL.md, without
|
||||
any transport. The gateway feeds it decoded messages (`handle`) and gives it
|
||||
a thread-safe `send(message)`; it never blocks the caller -- every request
|
||||
runs in the session's own small pool, values come from a live_values
|
||||
LiveReader (monitored where possible, polled otherwise, exactly as in the
|
||||
Qt and ipywidgets grids), writes go through live_values.start_write.
|
||||
|
||||
Values are coalesced: `flush()` returns at most one "values" event with the
|
||||
latest value per item since the last flush; the gateway calls it on a timer
|
||||
(FLUSH_INTERVAL), so a fast channel cannot flood a phone on a tunnel.
|
||||
"""
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from eco.web import viewmodels
|
||||
from eco.web.backends import NotFound
|
||||
from eco.widgets import live_values
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
PROTOCOL_VERSION = 0
|
||||
FLUSH_INTERVAL = 0.1 # s
|
||||
REQUEST_WORKERS = 4
|
||||
|
||||
|
||||
class ProtocolError(Exception):
|
||||
"""A request the client got wrong; reported back as error type ProtocolError."""
|
||||
|
||||
|
||||
class WritesDisabled(PermissionError):
|
||||
pass
|
||||
|
||||
|
||||
def _error(exc):
|
||||
return {"type": type(exc).__name__, "message": live_values.describe(exc)}
|
||||
|
||||
|
||||
class ClientSession:
|
||||
"""`writes`: False (read-only, the default), True, or a collection of
|
||||
item names that may be written (anything else is read-only)."""
|
||||
|
||||
def __init__(self, backend, send, writes=False, poll_interval=1.0, client_id=None):
|
||||
self.backend = backend
|
||||
self.send = send
|
||||
self.writes = writes
|
||||
self.client_id = client_id
|
||||
self._pool = ThreadPoolExecutor(max_workers=REQUEST_WORKERS, thread_name_prefix="eco-web")
|
||||
self._lock = threading.Lock()
|
||||
self._objects = {} # name -> object, every row/view handed to this client
|
||||
self._index = {} # name -> LiveReader index
|
||||
self._names = [] # LiveReader index -> name
|
||||
self._last = {} # name -> last raw value (types the next write)
|
||||
self._pending = {} # name -> encoded value, not yet flushed
|
||||
self._holders = {} # name -> {"changer": ...} of the latest write
|
||||
self._closed = False
|
||||
self._reader = live_values.LiveReader(self._on_result, poll_interval=poll_interval)
|
||||
self._reader.start()
|
||||
|
||||
# -- transport side ----------------------------------------------------------------
|
||||
|
||||
def handle(self, message):
|
||||
"""A decoded client message. Returns at once; the reply is sent later."""
|
||||
if not isinstance(message, dict) or "op" not in message:
|
||||
self.send({"v": PROTOCOL_VERSION, "re": None, "ok": False,
|
||||
"error": {"type": "ProtocolError", "message": "not a request"}})
|
||||
return
|
||||
request_id = message.get("id")
|
||||
op = message.get("op")
|
||||
args = message.get("args") or {}
|
||||
handler = getattr(self, f"_op_{op}", None) if isinstance(op, str) else None
|
||||
if handler is None:
|
||||
self._reply(request_id, error=ProtocolError(f"unknown op {op!r}"))
|
||||
return
|
||||
try:
|
||||
self._pool.submit(self._run, handler, request_id, args)
|
||||
except RuntimeError: # closed
|
||||
pass
|
||||
|
||||
def flush(self):
|
||||
"""The coalesced "values" event since the last flush, or None."""
|
||||
with self._lock:
|
||||
if not self._pending:
|
||||
return None
|
||||
data, self._pending = self._pending, {}
|
||||
return {"v": PROTOCOL_VERSION, "ev": "values", "now": time.time(), "data": data}
|
||||
|
||||
def close(self):
|
||||
self._closed = True
|
||||
self._reader.stop()
|
||||
self._pool.shutdown(wait=False, cancel_futures=True)
|
||||
|
||||
# -- plumbing ------------------------------------------------------------------------
|
||||
|
||||
def _run(self, handler, request_id, args):
|
||||
try:
|
||||
data = handler(**args)
|
||||
except TypeError as exc:
|
||||
self._reply(request_id, error=ProtocolError(f"bad arguments: {exc}"))
|
||||
except Exception as exc:
|
||||
self._reply(request_id, error=exc)
|
||||
else:
|
||||
self._reply(request_id, data=data)
|
||||
|
||||
def _reply(self, request_id, data=None, error=None):
|
||||
if self._closed:
|
||||
return
|
||||
message = {"v": PROTOCOL_VERSION, "re": request_id, "ok": error is None}
|
||||
if error is None:
|
||||
message["data"] = data
|
||||
else:
|
||||
message["error"] = _error(error)
|
||||
self.send(message)
|
||||
|
||||
def _event(self, name, data):
|
||||
if not self._closed:
|
||||
self.send({"v": PROTOCOL_VERSION, "ev": name, "data": data})
|
||||
|
||||
def _object(self, name):
|
||||
with self._lock:
|
||||
obj = self._objects.get(name)
|
||||
if obj is None:
|
||||
raise NotFound(f"{name!r} is not open in this client (describe it first)")
|
||||
return obj
|
||||
|
||||
def _may_write(self, name):
|
||||
if self.writes is True:
|
||||
return True
|
||||
if not self.writes:
|
||||
return False
|
||||
return name in self.writes
|
||||
|
||||
def _check_write(self, name):
|
||||
if not self._may_write(name):
|
||||
raise WritesDisabled(f"writing {name} is not enabled for this web session")
|
||||
return self._object(name)
|
||||
|
||||
def _on_result(self, index, ok, payload): # LiveReader pool threads
|
||||
name = self._names[index]
|
||||
if ok:
|
||||
self._last[name] = payload
|
||||
encoded = viewmodels.encode_value(payload)
|
||||
encoded["state"] = self._reader.monitor_state(index) or "polled"
|
||||
else:
|
||||
encoded = {"error": str(payload), "state": "error"}
|
||||
encoded["t"] = time.time()
|
||||
with self._lock:
|
||||
self._pending[name] = encoded
|
||||
|
||||
# -- operations ------------------------------------------------------------------------
|
||||
|
||||
def _op_hello(self, client_version=None, client_id=None):
|
||||
if client_id:
|
||||
self.client_id = client_id
|
||||
return {
|
||||
"protocol": PROTOCOL_VERSION,
|
||||
"label": self.backend.label,
|
||||
"mode": "session",
|
||||
"writes": bool(self.writes),
|
||||
"flush_interval": FLUSH_INTERVAL,
|
||||
}
|
||||
|
||||
def _op_ping(self):
|
||||
"""The client's liveness check: a network drop without a close
|
||||
frame (phone changing networks, tunnel dying) is only noticed by a
|
||||
reply that does not come."""
|
||||
return {}
|
||||
|
||||
def _op_names(self):
|
||||
return self.backend.names()
|
||||
|
||||
def _op_describe(self, name):
|
||||
with self._lock:
|
||||
obj = self._objects.get(name)
|
||||
if obj is None:
|
||||
obj = self.backend.resolve(name) # top-level: may initialize a lazy one
|
||||
view, objects = viewmodels.describe(obj, name)
|
||||
objects.setdefault(name, obj)
|
||||
with self._lock:
|
||||
self._objects.update(objects)
|
||||
for row in view["rows"]:
|
||||
row["writable"] = row["writable"] and self._may_write(row["name"])
|
||||
view["writable"] = self._may_write(name)
|
||||
return view
|
||||
|
||||
def _op_subscribe(self, names):
|
||||
for name in names:
|
||||
obj = self._object(name)
|
||||
with self._lock:
|
||||
index = self._index.get(name)
|
||||
if index is None:
|
||||
self._names.append(name)
|
||||
index = self._index[name] = self._reader.add(obj)
|
||||
continue
|
||||
self._reader.set_active(index, True)
|
||||
return {"subscribed": list(names)}
|
||||
|
||||
def _op_unsubscribe(self, names):
|
||||
for name in names:
|
||||
with self._lock:
|
||||
index = self._index.get(name)
|
||||
self._pending.pop(name, None)
|
||||
if index is not None:
|
||||
self._reader.set_active(index, False)
|
||||
return {"unsubscribed": list(names)}
|
||||
|
||||
def _start_write(self, name, target_fn):
|
||||
obj = self._check_write(name)
|
||||
holder = self._holders.setdefault(name, {})
|
||||
|
||||
def on_state(state, message):
|
||||
self._event("write", {"name": name, "state": state, "message": message})
|
||||
|
||||
def on_finished():
|
||||
index = self._index.get(name)
|
||||
if index is not None:
|
||||
self._reader.request_read(index)
|
||||
|
||||
self._event("write", {"name": name, "state": "busy", "message": ""})
|
||||
live_values.start_write(obj, target_fn, on_state, on_finished=on_finished, holder=holder)
|
||||
logger.info("web client %s writes %s", self.client_id, name)
|
||||
return {"started": name}
|
||||
|
||||
def _op_set(self, name, value):
|
||||
last = self._last.get(name)
|
||||
target = viewmodels.coerce_target(value, last) if last is not None else value
|
||||
return self._start_write(name, lambda: target)
|
||||
|
||||
def _op_step(self, name, sign, step):
|
||||
sign = 1 if float(sign) > 0 else -1
|
||||
step = abs(float(step))
|
||||
obj = self._check_write(name)
|
||||
return self._start_write(name, lambda: obj.get_current_value() + sign * step)
|
||||
|
||||
def _op_stop(self, name):
|
||||
obj = self._check_write(name)
|
||||
holder = self._holders.get(name, {})
|
||||
|
||||
def on_state(state, message):
|
||||
self._event("write", {"name": name, "state": state, "message": message})
|
||||
|
||||
live_values.stop_move(obj, holder.get("changer"), on_state)
|
||||
return {"stopping": name}
|
||||
|
||||
def _op_trigger(self, name):
|
||||
obj = self._check_write(name)
|
||||
|
||||
def run():
|
||||
try:
|
||||
obj.trigger()
|
||||
self._event("write", {"name": name, "state": "idle", "message": "triggered"})
|
||||
except Exception as exc:
|
||||
self._event("write", {"name": name, "state": "error", "message": live_values.describe(exc)})
|
||||
|
||||
threading.Thread(target=run, daemon=True).start()
|
||||
return {"triggered": name}
|
||||
|
||||
def _op_step_size(self, name):
|
||||
"""The tweak step a ▲/▼ pair starts with (the grids' initial_step:
|
||||
the adjustable's own tweak step, else 1 / 0.1)."""
|
||||
obj = self._object(name)
|
||||
value = self._last.get(name)
|
||||
if value is None:
|
||||
value = obj.get_current_value()
|
||||
return {"step": live_values.initial_step(obj, value)}
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
"""A simulated namespace for developing and trying the web client without a
|
||||
beamline: motors that take time to move, noisy detectors, valves, an enum
|
||||
selector, a trigger, an SVG panel, a component that initializes slowly and
|
||||
one that fails. Pure Python, no EPICS.
|
||||
|
||||
python -m eco.web --demo # serve it (read-only)
|
||||
python -m eco.web --demo --writes # with writes
|
||||
"""
|
||||
import enum
|
||||
import math
|
||||
import random
|
||||
import threading
|
||||
import time
|
||||
|
||||
from eco.aliases.aliases import Alias
|
||||
from eco.elements.adjustable import AdjustableMemory, AdjustableTrigger
|
||||
from eco.elements.assembly import Assembly
|
||||
|
||||
|
||||
class _Changer:
|
||||
def __init__(self, done):
|
||||
self._done = done
|
||||
self.stopped = False
|
||||
|
||||
def wait(self):
|
||||
self._done.wait()
|
||||
|
||||
def stop(self):
|
||||
self.stopped = True
|
||||
|
||||
|
||||
class SimMotor:
|
||||
"""Moves linearly at `speed` units/s; stoppable; soft limits."""
|
||||
|
||||
def __init__(self, value=0.0, speed=1.0, limits=(-100, 100), unit="mm", name=None):
|
||||
self.name = name
|
||||
self.alias = Alias(name)
|
||||
self.unit = unit
|
||||
self.speed = speed
|
||||
self.limits = limits
|
||||
self._value = float(value)
|
||||
self._lock = threading.Lock()
|
||||
self._changer = None
|
||||
|
||||
def get_current_value(self):
|
||||
return round(self._value, 6)
|
||||
|
||||
def set_target_value(self, value):
|
||||
value = float(value)
|
||||
low, high = self.limits
|
||||
if not low <= value <= high:
|
||||
raise ValueError(f"{self.name}: {value} outside limits {self.limits}")
|
||||
if self._changer is not None:
|
||||
self._changer.stop()
|
||||
done = threading.Event()
|
||||
changer = self._changer = _Changer(done)
|
||||
|
||||
def run():
|
||||
dt = 0.05
|
||||
while not changer.stopped:
|
||||
with self._lock:
|
||||
delta = value - self._value
|
||||
step = math.copysign(min(abs(delta), self.speed * dt), delta)
|
||||
self._value += step
|
||||
if abs(value - self._value) < 1e-9:
|
||||
break
|
||||
time.sleep(dt)
|
||||
done.set()
|
||||
|
||||
threading.Thread(target=run, daemon=True).start()
|
||||
return changer
|
||||
|
||||
def stop(self):
|
||||
if self._changer is not None:
|
||||
self._changer.stop()
|
||||
|
||||
|
||||
class SimDetector:
|
||||
def __init__(self, center=1.0, noise=0.05, unit=None, log=False, name=None):
|
||||
self.name = name
|
||||
self.alias = Alias(name)
|
||||
self.unit = unit
|
||||
self.center = center
|
||||
self.noise = noise
|
||||
self.log = log
|
||||
|
||||
def get_current_value(self):
|
||||
if self.log:
|
||||
return self.center * 10 ** random.gauss(0, self.noise)
|
||||
return self.center + random.gauss(0, self.noise)
|
||||
|
||||
|
||||
class ValveState(enum.Enum):
|
||||
closed = 0
|
||||
open = 1
|
||||
|
||||
|
||||
class SimValve:
|
||||
def __init__(self, open=True, name=None):
|
||||
self.name = name
|
||||
self.alias = Alias(name)
|
||||
self._state = ValveState.open if open else ValveState.closed
|
||||
|
||||
def get_current_value(self):
|
||||
return self._state
|
||||
|
||||
def set_target_value(self, value):
|
||||
if isinstance(value, str):
|
||||
value = ValveState[value]
|
||||
elif not isinstance(value, ValveState):
|
||||
value = ValveState(int(value))
|
||||
done = threading.Event()
|
||||
|
||||
def run():
|
||||
time.sleep(0.8)
|
||||
self._state = value
|
||||
done.set()
|
||||
|
||||
threading.Thread(target=run, daemon=True).start()
|
||||
return _Changer(done)
|
||||
|
||||
|
||||
class Mono(Assembly):
|
||||
def __init__(self, name=None):
|
||||
super().__init__(name=name)
|
||||
self._append(SimMotor, 7.0, speed=0.2, limits=(4, 20), unit="keV", name="energy", is_display=True)
|
||||
self._append(SimMotor, 15.0, speed=0.5, limits=(5, 40), unit="deg", name="bragg", is_display=True)
|
||||
self._append(SimDetector, 0.0, 0.002, unit="urad", name="pitch_rbv", is_display=True)
|
||||
self._append(AdjustableMemory, 3, name="harmonic", is_display=True)
|
||||
self._append(AdjustableTrigger, lambda: time.sleep(1), name="home_all", is_display=True)
|
||||
|
||||
|
||||
class Slits(Assembly):
|
||||
def __init__(self, name=None):
|
||||
super().__init__(name=name)
|
||||
self._append(SimMotor, 1.0, speed=0.5, limits=(0, 10), name="hgap", is_display=True)
|
||||
self._append(SimMotor, 1.0, speed=0.5, limits=(0, 10), name="vgap", is_display=True)
|
||||
self._append(SimMotor, 0.0, speed=0.5, limits=(-5, 5), name="hpos", is_display=True)
|
||||
self._append(SimMotor, 0.0, speed=0.5, limits=(-5, 5), name="vpos", is_display=True)
|
||||
self._append(SimMotor, 0.0, speed=0.2, limits=(-5, 5), name="blade_offset", is_display=False)
|
||||
|
||||
|
||||
class Vacuum(Assembly):
|
||||
"""A short vacuum section with an SVG panel (like PrepumpSystem/Beamline)."""
|
||||
|
||||
def __init__(self, name=None):
|
||||
super().__init__(name=name)
|
||||
for i, open_ in enumerate([True, True, False], start=1):
|
||||
self._append(SimValve, open_, name=f"valve{i}", is_display=True)
|
||||
for i, center in enumerate([1e-7, 3e-6, 2e-2], start=1):
|
||||
self._append(SimDetector, center, 0.1, unit="mbar", log=True, name=f"gauge{i}", is_display=True)
|
||||
|
||||
def _widget_svg_panel(self, path=None, live=True):
|
||||
from eco.utilities.tempfiles import user_temp_svg_path
|
||||
|
||||
parts = ['<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 160" font-family="sans-serif">',
|
||||
'<line x1="20" y1="80" x2="620" y2="80" stroke="#888" stroke-width="6"/>']
|
||||
for i in range(3):
|
||||
x = 100 + i * 200
|
||||
valve = getattr(self, f"valve{i + 1}")
|
||||
gauge = getattr(self, f"gauge{i + 1}")
|
||||
color = "#888"
|
||||
pressure = ""
|
||||
if live:
|
||||
color = "#2e9d4a" if valve.get_current_value() is ValveState.open else "#d93025"
|
||||
pressure = f"{gauge.get_current_value():.1e}"
|
||||
parts.append(f'<g style="cursor:pointer" onclick="// eco: valve{i + 1}"><desc>valve{i + 1}</desc>'
|
||||
f'<polygon points="{x - 20},60 {x + 20},100 {x + 20},60 {x - 20},100" fill="{color}" stroke="#333"/>'
|
||||
f'<text x="{x}" y="125" text-anchor="middle" font-size="13">valve{i + 1}</text></g>')
|
||||
gx = x + 90
|
||||
parts.append(f'<g style="cursor:pointer" onclick="// eco: gauge{i + 1}"><desc>gauge{i + 1}</desc>'
|
||||
f'<circle cx="{gx}" cy="45" r="14" fill="#fff" stroke="#333"/>'
|
||||
f'<text x="{gx}" y="20" text-anchor="middle" font-size="12">{pressure}</text>'
|
||||
f'<line x1="{gx}" y1="59" x2="{gx}" y2="80" stroke="#333"/></g>')
|
||||
parts.append("</svg>")
|
||||
path = path or user_temp_svg_path("eco_web_demo", self.name)
|
||||
with open(path, "w") as f:
|
||||
f.write("".join(parts))
|
||||
return path
|
||||
|
||||
|
||||
class SlowDevice(Assembly):
|
||||
def __init__(self, name=None):
|
||||
time.sleep(2.0)
|
||||
super().__init__(name=name)
|
||||
self._append(SimDetector, 42.0, 0.5, name="reading", is_display=True)
|
||||
|
||||
|
||||
def _broken(name=None):
|
||||
raise ConnectionError("simulated: IOC not reachable")
|
||||
|
||||
|
||||
class DemoNamespace:
|
||||
"""Just the parts of eco.utilities.config.Namespace the web backend uses."""
|
||||
|
||||
name = "demo"
|
||||
|
||||
def __init__(self):
|
||||
self.initialized_items = {}
|
||||
self.lazy_items = {}
|
||||
self.failed_items = {}
|
||||
self.failed_items_excpetion = {}
|
||||
self._factories = {
|
||||
"mono": Mono,
|
||||
"slits": Slits,
|
||||
"vacuum": Vacuum,
|
||||
"lxt": lambda name=None: SimMotor(0.0, speed=2e-12, limits=(-1e-9, 1e-9), unit="s", name=name),
|
||||
"slow_device": SlowDevice,
|
||||
"broken": _broken,
|
||||
}
|
||||
for name in ("mono", "lxt"):
|
||||
self.init_name(name)
|
||||
for name in ("slits", "vacuum", "slow_device", "broken"):
|
||||
self.lazy_items[name] = name
|
||||
self.init_name("broken")
|
||||
|
||||
@property
|
||||
def initialized_names(self):
|
||||
return set(self.initialized_items)
|
||||
|
||||
@property
|
||||
def lazy_names(self):
|
||||
return set(self.lazy_items)
|
||||
|
||||
@property
|
||||
def failed_names(self):
|
||||
return set(self.failed_items)
|
||||
|
||||
@property
|
||||
def all_names(self):
|
||||
return self.initialized_names | self.lazy_names | self.failed_names
|
||||
|
||||
def resolve_item(self, name):
|
||||
for items in (self.lazy_items, self.failed_items, self.initialized_items):
|
||||
if name in items:
|
||||
return items[name]
|
||||
return None
|
||||
|
||||
def init_name(self, name, verbose=True, raise_errors=False, quiet=False):
|
||||
self.lazy_items.pop(name, None)
|
||||
try:
|
||||
self.initialized_items[name] = self._factories[name](name=name)
|
||||
except Exception as exc:
|
||||
self.failed_items[name] = None
|
||||
self.failed_items_excpetion[name] = exc
|
||||
if raise_errors:
|
||||
raise
|
||||
@@ -0,0 +1,302 @@
|
||||
"""The HTTP/websocket server behind the eco web client (PWA).
|
||||
|
||||
Runs tornado on its own thread with its own event loop: it never needs the
|
||||
session's main thread (so eco.utilities.mainthread does not concern it) and
|
||||
never touches hardware on its loop -- ClientSession does all of that in its
|
||||
pools.
|
||||
|
||||
Security model (web_frontend/ARCHITECTURE.md §6/§7): binds 127.0.0.1 by
|
||||
default, so reaching it takes an SSH login to the host (``ssh -L``); a
|
||||
per-gateway token is required on top, since every account on a shared
|
||||
console host can reach 127.0.0.1. The token comes once in the URL
|
||||
(``/?token=...``) and is then kept in an HttpOnly cookie, so the installed
|
||||
app reopens without it. Writes are off unless the gateway was started with
|
||||
them.
|
||||
"""
|
||||
import asyncio
|
||||
import hmac
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
import tornado.web
|
||||
import tornado.websocket
|
||||
from tornado.ioloop import IOLoop, PeriodicCallback
|
||||
|
||||
from eco.web.backends import NotFound
|
||||
from eco.web.client_session import FLUSH_INTERVAL, ClientSession
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
STATIC_DIR = os.path.join(os.path.dirname(__file__), "static")
|
||||
COOKIE = "eco_web_token"
|
||||
DEFAULT_PORT = 8097
|
||||
_ROOT_FILES = ("sw.js", "manifest.webmanifest", "icon.svg") # served at / for the PWA scope
|
||||
|
||||
|
||||
class _Base(tornado.web.RequestHandler):
|
||||
@property
|
||||
def gateway(self):
|
||||
return self.application.settings["gateway"]
|
||||
|
||||
def authorized(self):
|
||||
given = self.get_query_argument("token", None) or self.get_cookie(COOKIE)
|
||||
return bool(given) and hmac.compare_digest(given, self.gateway.token)
|
||||
|
||||
def set_default_headers(self):
|
||||
self.set_header("Cache-Control", "no-cache")
|
||||
self.set_header("X-Content-Type-Options", "nosniff")
|
||||
|
||||
|
||||
class _Index(_Base):
|
||||
def get(self):
|
||||
token = self.get_query_argument("token", None)
|
||||
if token is not None:
|
||||
if not hmac.compare_digest(token, self.gateway.token):
|
||||
raise tornado.web.HTTPError(403)
|
||||
self.set_cookie(COOKIE, token, httponly=True, samesite="Strict", expires_days=30)
|
||||
self.redirect("/") # keep the token out of history and the installed app's start URL
|
||||
return
|
||||
if not self.authorized():
|
||||
self.set_status(403)
|
||||
self.finish("eco web: open the URL with ?token=... printed by eco.web.start_web()")
|
||||
return
|
||||
with open(os.path.join(STATIC_DIR, "index.html"), "rb") as f:
|
||||
self.set_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.finish(f.read())
|
||||
|
||||
|
||||
class _RootFile(_Base):
|
||||
def get(self, filename):
|
||||
path = os.path.join(STATIC_DIR, filename)
|
||||
types = {".js": "text/javascript", ".webmanifest": "application/manifest+json", ".svg": "image/svg+xml"}
|
||||
self.set_header("Content-Type", types[os.path.splitext(filename)[1]])
|
||||
with open(path, "rb") as f:
|
||||
self.finish(f.read())
|
||||
|
||||
|
||||
class _Svg(_Base):
|
||||
async def get(self):
|
||||
if not self.authorized():
|
||||
raise tornado.web.HTTPError(403)
|
||||
name = self.get_query_argument("name")
|
||||
live = self.get_query_argument("live", "1") != "0"
|
||||
try:
|
||||
text, prefix = await IOLoop.current().run_in_executor(
|
||||
self.gateway.svg_pool, self.gateway.svg_for, name, live
|
||||
)
|
||||
except NotFound as exc:
|
||||
raise tornado.web.HTTPError(404, reason=str(exc)[:200])
|
||||
self.set_header("Content-Type", "image/svg+xml; charset=utf-8")
|
||||
self.set_header("X-Eco-Prefix", prefix)
|
||||
self.finish(text)
|
||||
|
||||
|
||||
class _Socket(tornado.websocket.WebSocketHandler):
|
||||
@property
|
||||
def gateway(self):
|
||||
return self.application.settings["gateway"]
|
||||
|
||||
def open(self):
|
||||
given = self.get_query_argument("token", None) or self.get_cookie(COOKIE)
|
||||
if not given or not hmac.compare_digest(given, self.gateway.token):
|
||||
self.close(4403, "not authorized")
|
||||
return
|
||||
loop = IOLoop.current()
|
||||
|
||||
def send(message): # any thread
|
||||
try:
|
||||
loop.add_callback(self._send, message)
|
||||
except RuntimeError: # loop closed: the gateway is stopping
|
||||
pass
|
||||
|
||||
self.session = ClientSession(
|
||||
self.gateway.backend, send, writes=self.gateway.writes,
|
||||
poll_interval=self.gateway.poll_interval,
|
||||
)
|
||||
self.gateway.sessions.add(self)
|
||||
|
||||
def _send(self, message):
|
||||
if self.ws_connection is None:
|
||||
return
|
||||
try:
|
||||
self.write_message(json.dumps(message, default=str))
|
||||
except tornado.websocket.WebSocketClosedError:
|
||||
pass
|
||||
|
||||
def on_message(self, raw):
|
||||
session = getattr(self, "session", None)
|
||||
if session is None:
|
||||
return
|
||||
try:
|
||||
message = json.loads(raw)
|
||||
except ValueError:
|
||||
message = None
|
||||
session.handle(message)
|
||||
|
||||
def flush_values(self):
|
||||
session = getattr(self, "session", None)
|
||||
if session is not None:
|
||||
event = session.flush()
|
||||
if event is not None:
|
||||
self._send(event)
|
||||
|
||||
def on_close(self): # also called by WebGateway.stop: idempotent
|
||||
self.gateway.sessions.discard(self)
|
||||
session = self.__dict__.pop("session", None)
|
||||
if session is not None:
|
||||
session.close()
|
||||
|
||||
|
||||
TOKEN_FILE = os.path.join(os.path.expanduser("~"), ".eco", "web_token")
|
||||
|
||||
|
||||
def persistent_token(path=TOKEN_FILE):
|
||||
"""This account's token, kept in `path` (mode 0600) so that a bookmarked
|
||||
or installed client keeps working across gateway restarts. Delete the
|
||||
file to invalidate every client that has it. Falls back to a fresh token
|
||||
if the file cannot be written."""
|
||||
try:
|
||||
with open(path) as f:
|
||||
token = f.read().strip()
|
||||
if token:
|
||||
return token
|
||||
except OSError:
|
||||
pass
|
||||
token = secrets.token_urlsafe(18)
|
||||
try:
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
with os.fdopen(fd, "w") as f:
|
||||
f.write(token + "\n")
|
||||
except OSError:
|
||||
logger.warning("could not store the web token in %s; it changes with every start", path)
|
||||
return token
|
||||
|
||||
|
||||
class WebGateway:
|
||||
"""`token`: None (default) uses this account's persistent token
|
||||
(persistent_token), "random" a fresh one per start, anything else is
|
||||
used as given."""
|
||||
|
||||
def __init__(self, backend, host="127.0.0.1", port=DEFAULT_PORT, token=None,
|
||||
writes=False, poll_interval=1.0):
|
||||
self.backend = backend
|
||||
self.host = host
|
||||
self.port = port
|
||||
if token is None:
|
||||
token = persistent_token()
|
||||
elif token == "random":
|
||||
token = secrets.token_urlsafe(18)
|
||||
self.token = token
|
||||
self.writes = writes
|
||||
self.poll_interval = poll_interval
|
||||
self.sessions = set()
|
||||
self.svg_pool = ThreadPoolExecutor(max_workers=2, thread_name_prefix="eco-web-svg")
|
||||
self._svg_objects = {}
|
||||
self._loop = None
|
||||
self._thread = None
|
||||
self._server = None
|
||||
self._ready = threading.Event()
|
||||
self._error = None
|
||||
|
||||
# -- lifecycle ------------------------------------------------------------------------
|
||||
|
||||
def make_app(self):
|
||||
return tornado.web.Application(
|
||||
[
|
||||
(r"/", _Index),
|
||||
(r"/(%s)" % "|".join(re.escape(f) for f in _ROOT_FILES), _RootFile),
|
||||
(r"/static/(.*)", tornado.web.StaticFileHandler, {"path": STATIC_DIR}),
|
||||
(r"/api/svg", _Svg),
|
||||
(r"/ws", _Socket),
|
||||
],
|
||||
gateway=self,
|
||||
websocket_ping_interval=20,
|
||||
)
|
||||
|
||||
def start(self, timeout=10.0):
|
||||
"""Serve on a background thread; returns once listening."""
|
||||
if self._thread is not None:
|
||||
return self
|
||||
self._thread = threading.Thread(target=self._serve, name="eco-web-gateway", daemon=True)
|
||||
self._thread.start()
|
||||
if not self._ready.wait(timeout):
|
||||
raise TimeoutError("eco web gateway did not start")
|
||||
if self._error is not None:
|
||||
self._thread = None
|
||||
raise self._error
|
||||
return self
|
||||
|
||||
def _serve(self):
|
||||
asyncio.set_event_loop(asyncio.new_event_loop())
|
||||
self._loop = IOLoop.current()
|
||||
try:
|
||||
self._server = self.make_app().listen(self.port, address=self.host)
|
||||
if self.port == 0: # tests: an ephemeral port
|
||||
self.port = next(iter(self._server._sockets.values())).getsockname()[1]
|
||||
except Exception as exc:
|
||||
self._error = exc
|
||||
self._ready.set()
|
||||
return
|
||||
PeriodicCallback(self._flush_all, FLUSH_INTERVAL * 1000).start()
|
||||
self._ready.set()
|
||||
self._loop.start()
|
||||
|
||||
def _flush_all(self):
|
||||
for handler in list(self.sessions):
|
||||
handler.flush_values()
|
||||
|
||||
def stop(self):
|
||||
loop = self._loop
|
||||
if loop is None:
|
||||
return
|
||||
|
||||
async def _shutdown():
|
||||
if self._server is not None:
|
||||
self._server.stop()
|
||||
for handler in list(self.sessions):
|
||||
handler.close(1001, "gateway stopped") # clients see it at once and reconnect
|
||||
await asyncio.sleep(0.2) # let the close frames go out
|
||||
for handler in list(self.sessions):
|
||||
handler.on_close()
|
||||
loop.stop()
|
||||
|
||||
loop.add_callback(_shutdown)
|
||||
if self._thread is not None:
|
||||
self._thread.join(5)
|
||||
try:
|
||||
loop.close(all_fds=True)
|
||||
except Exception:
|
||||
pass
|
||||
self._thread = None
|
||||
self._loop = None
|
||||
self.svg_pool.shutdown(wait=False, cancel_futures=True)
|
||||
|
||||
@property
|
||||
def running(self):
|
||||
return self._thread is not None and self._thread.is_alive()
|
||||
|
||||
# -- helpers ----------------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
def url(self):
|
||||
return f"http://localhost:{self.port}/?token={self.token}"
|
||||
|
||||
def svg_for(self, name, live):
|
||||
"""Resolve `name` -- any name a client has seen (top-level or a row)
|
||||
-- and build its panel. Row names come from client sessions."""
|
||||
obj = None
|
||||
for handler in list(self.sessions):
|
||||
session = getattr(handler, "session", None)
|
||||
if session is not None:
|
||||
obj = session._objects.get(name)
|
||||
if obj is not None:
|
||||
break
|
||||
if obj is None:
|
||||
obj = self.backend.resolve(name)
|
||||
return self.backend.svg(obj, live=live)
|
||||
@@ -0,0 +1,519 @@
|
||||
// eco web client -- talks web_frontend/PROTOCOL.md (v0) to eco.web.gateway.
|
||||
// Plain ES module, no build step, no dependencies. DOM is built with
|
||||
// textContent only (never innerHTML from server data); SVG panels are
|
||||
// sanitized before insertion (sanitizeSvg).
|
||||
|
||||
const VERSION = "0.1";
|
||||
const STALE_AFTER = 35; // s without a fresh read -> greyed (monitored items are re-read at least every 10 s)
|
||||
const SHOW_AGE_AFTER = 12; // s
|
||||
const SVG_REFRESH = 3000; // ms
|
||||
const PING_EVERY = 15000; // ms -- a dropped network sends no close frame; only a missing reply shows it
|
||||
const PING_TIMEOUT = 8000; // ms
|
||||
const DOT = { waiting: "var(--wait)", live: "var(--ok)", subscribed: "var(--ok)", polled: "var(--polled)",
|
||||
busy: "var(--busy)", moving: "var(--busy)", error: "var(--err)" };
|
||||
|
||||
const S = {
|
||||
ws: null, nextId: 0, pending: new Map(), hello: null, retry: 0, retryTimer: null,
|
||||
offset: 0, // client clock - gateway clock, s
|
||||
view: null, // current view: {kind, name, subscribed: [], rows: Map, timers: []}
|
||||
filter: "",
|
||||
};
|
||||
|
||||
// ---- small DOM helpers ------------------------------------------------------------
|
||||
|
||||
function el(tag, attrs = {}, ...children) {
|
||||
const node = document.createElement(tag);
|
||||
for (const [key, value] of Object.entries(attrs)) {
|
||||
if (value === undefined || value === null || value === false) continue;
|
||||
if (key === "class") node.className = value;
|
||||
else if (key === "text") node.textContent = value;
|
||||
else if (key.startsWith("on")) node.addEventListener(key.slice(2), value);
|
||||
else node.setAttribute(key, value === true ? "" : value);
|
||||
}
|
||||
for (const child of children.flat()) {
|
||||
if (child === null || child === undefined || child === false) continue;
|
||||
node.append(child instanceof Node ? child : document.createTextNode(String(child)));
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
const main = () => document.getElementById("main");
|
||||
|
||||
function setMain(...children) {
|
||||
main().replaceChildren(...children);
|
||||
}
|
||||
|
||||
function toast(message, isError = false) {
|
||||
const box = document.getElementById("toast");
|
||||
box.textContent = message;
|
||||
box.className = isError ? "err" : "";
|
||||
box.hidden = false;
|
||||
clearTimeout(toast.timer);
|
||||
toast.timer = setTimeout(() => (box.hidden = true), isError ? 6000 : 2500);
|
||||
}
|
||||
|
||||
function banner(message) {
|
||||
const box = document.getElementById("banner");
|
||||
box.textContent = message || "";
|
||||
box.hidden = !message;
|
||||
}
|
||||
|
||||
function setTitle(text, withBack) {
|
||||
document.getElementById("title").textContent = text;
|
||||
document.title = text === "eco" ? "eco" : `${text} – eco`;
|
||||
document.getElementById("back").hidden = !withBack;
|
||||
}
|
||||
|
||||
function setConn(state) {
|
||||
const dot = document.getElementById("conn");
|
||||
dot.className = "conn " + state;
|
||||
dot.title = { up: "connected", down: "disconnected", "": "connecting" }[state] ?? state;
|
||||
}
|
||||
|
||||
function clientId() {
|
||||
try {
|
||||
let id = localStorage.getItem("eco-web-client");
|
||||
if (!id) {
|
||||
id = Math.random().toString(36).slice(2, 10);
|
||||
localStorage.setItem("eco-web-client", id);
|
||||
}
|
||||
return id;
|
||||
} catch {
|
||||
return "anon";
|
||||
}
|
||||
}
|
||||
|
||||
function formatNum(n) {
|
||||
if (Number.isInteger(n)) return String(n);
|
||||
const a = Math.abs(n);
|
||||
if (a !== 0 && (a < 1e-3 || a >= 1e6)) return n.toExponential(4);
|
||||
return String(+n.toPrecision(7));
|
||||
}
|
||||
|
||||
// ---- connection ------------------------------------------------------------------------
|
||||
|
||||
function connect() {
|
||||
clearTimeout(S.retryTimer);
|
||||
setConn("");
|
||||
const proto = location.protocol === "https:" ? "wss:" : "ws:";
|
||||
const ws = new WebSocket(`${proto}//${location.host}/ws`);
|
||||
S.ws = ws;
|
||||
ws.onopen = async () => {
|
||||
S.retry = 0;
|
||||
setConn("up");
|
||||
banner("");
|
||||
clearInterval(S.pingTimer);
|
||||
S.pingTimer = setInterval(() => {
|
||||
if (S.ws !== ws) return clearInterval(S.pingTimer);
|
||||
const timeout = new Promise((_, reject) => setTimeout(() => reject(new Error("ping timeout")), PING_TIMEOUT));
|
||||
Promise.race([request("ping"), timeout]).catch(() => {
|
||||
lost(ws, { code: 0 }); // at once: close() on a dead connection can take minutes to report
|
||||
ws.close();
|
||||
});
|
||||
}, PING_EVERY);
|
||||
try {
|
||||
S.hello = await request("hello", { client_version: VERSION, client_id: clientId() });
|
||||
} catch (e) {
|
||||
banner(`hello failed: ${e.message}`);
|
||||
return;
|
||||
}
|
||||
const mode = document.getElementById("mode");
|
||||
mode.textContent = S.hello.writes ? "writes on" : "read-only";
|
||||
mode.className = "badge" + (S.hello.writes ? " writes" : "");
|
||||
route();
|
||||
};
|
||||
ws.onmessage = (event) => {
|
||||
let message;
|
||||
try {
|
||||
message = JSON.parse(event.data);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if ("re" in message) {
|
||||
const waiter = S.pending.get(message.re);
|
||||
if (!waiter) return;
|
||||
S.pending.delete(message.re);
|
||||
if (message.ok) waiter.resolve(message.data);
|
||||
else waiter.reject(Object.assign(new Error(message.error?.message || "error"), { type: message.error?.type }));
|
||||
} else if (message.ev) {
|
||||
onEvent(message);
|
||||
}
|
||||
};
|
||||
ws.onclose = (event) => lost(ws, event);
|
||||
}
|
||||
|
||||
function lost(ws, event) {
|
||||
if (S.ws !== ws) return;
|
||||
S.ws = null;
|
||||
clearInterval(S.pingTimer);
|
||||
setConn("down");
|
||||
for (const waiter of S.pending.values()) waiter.reject(new Error("disconnected"));
|
||||
S.pending.clear();
|
||||
if (event.code === 4403) {
|
||||
banner("Not authorized – open the URL with ?token=… printed by eco.web.start_web() once more.");
|
||||
return;
|
||||
}
|
||||
banner("Disconnected – reconnecting…");
|
||||
const delay = Math.min(10, 2 ** S.retry++) * 1000;
|
||||
S.retryTimer = setTimeout(connect, delay);
|
||||
}
|
||||
|
||||
function request(op, args = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!S.ws || S.ws.readyState !== WebSocket.OPEN) return reject(new Error("not connected"));
|
||||
const id = ++S.nextId;
|
||||
S.pending.set(id, { resolve, reject });
|
||||
S.ws.send(JSON.stringify({ v: 0, id, op, args }));
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
// phones suspend background tabs/apps: reconnect at once when shown again
|
||||
if (document.visibilityState === "visible" && (!S.ws || S.ws.readyState > WebSocket.OPEN)) {
|
||||
S.retry = 0;
|
||||
connect();
|
||||
}
|
||||
});
|
||||
|
||||
// ---- events -------------------------------------------------------------------------------
|
||||
|
||||
function onEvent(message) {
|
||||
if (message.ev === "values") {
|
||||
if (typeof message.now === "number") S.offset = Date.now() / 1000 - message.now;
|
||||
for (const [name, value] of Object.entries(message.data)) applyValue(name, value);
|
||||
} else if (message.ev === "write") {
|
||||
applyWrite(message.data);
|
||||
}
|
||||
}
|
||||
|
||||
function serverNow() {
|
||||
return Date.now() / 1000 - S.offset;
|
||||
}
|
||||
|
||||
// ---- routing ---------------------------------------------------------------------------------
|
||||
|
||||
function leaveView() {
|
||||
const view = S.view;
|
||||
S.view = null;
|
||||
if (!view) return;
|
||||
view.timers.forEach(clearInterval);
|
||||
if (view.subscribed.length) request("unsubscribe", { names: view.subscribed }).catch(() => {});
|
||||
}
|
||||
|
||||
function route() {
|
||||
leaveView();
|
||||
if (!S.hello) return;
|
||||
const hash = decodeURIComponent(location.hash.slice(1));
|
||||
if (hash.startsWith("/d/")) showDevice(hash.slice(3));
|
||||
else if (hash.startsWith("/svg/")) showSvg(hash.slice(5));
|
||||
else showHome();
|
||||
}
|
||||
|
||||
window.addEventListener("hashchange", route);
|
||||
document.getElementById("back").addEventListener("click", () => {
|
||||
if (history.length > 1) history.back();
|
||||
else location.hash = "";
|
||||
});
|
||||
|
||||
function newView(kind, name) {
|
||||
S.view = { kind, name, subscribed: [], rows: new Map(), timers: [] };
|
||||
return S.view;
|
||||
}
|
||||
|
||||
// ---- home: the namespace -----------------------------------------------------------------
|
||||
|
||||
async function showHome() {
|
||||
const view = newView("home", "");
|
||||
setTitle(S.hello.label || "eco", false);
|
||||
setMain(el("div", { class: "loading", text: "loading names…" }));
|
||||
let names;
|
||||
try {
|
||||
names = await request("names");
|
||||
} catch (e) {
|
||||
if (S.view === view) setMain(el("div", { class: "empty", text: `could not list names: ${e.message}` }));
|
||||
return;
|
||||
}
|
||||
if (S.view !== view) return;
|
||||
|
||||
const sections = el("div");
|
||||
const render = () => {
|
||||
const f = S.filter.toLowerCase();
|
||||
const match = (n) => !f || n.toLowerCase().includes(f);
|
||||
const item = (name, cls, note) =>
|
||||
el("a", { class: `item ${cls}`, href: `#/d/${encodeURIComponent(name)}` },
|
||||
el("span", { class: "name", text: name }), note ? el("span", { class: "note", text: note }) : null);
|
||||
const block = (title, list) => (list.length ? [el("div", { class: "section-title", text: title }), el("div", { class: "list" }, list)] : []);
|
||||
const failed = Object.entries(names.failed).filter(([n]) => match(n));
|
||||
sections.replaceChildren(
|
||||
...block("Initialized", names.initialized.filter(match).map((n) => item(n, "", ""))),
|
||||
...block("Not initialized – tap to initialize", names.lazy.filter(match).map((n) => item(n, "lazy", "lazy"))),
|
||||
...block("Failed", failed.map(([n, reason]) => item(n, "failed", reason.slice(0, 80)))),
|
||||
);
|
||||
if (!sections.childElementCount) sections.append(el("div", { class: "empty", text: "nothing matches" }));
|
||||
};
|
||||
const search = el("input", { class: "search", type: "search", placeholder: "filter components", value: S.filter,
|
||||
autocapitalize: "off", autocomplete: "off", spellcheck: "false",
|
||||
oninput: (e) => { S.filter = e.target.value; render(); } });
|
||||
render();
|
||||
setMain(search, sections);
|
||||
}
|
||||
|
||||
// ---- device: an assembly or a single item -----------------------------------------------------
|
||||
|
||||
async function showDevice(name) {
|
||||
const view = newView("device", name);
|
||||
setTitle(name, true);
|
||||
setMain(el("div", { class: "loading", text: `opening ${name}… (initializing it if needed)` }));
|
||||
let desc;
|
||||
try {
|
||||
desc = await request("describe", { name });
|
||||
} catch (e) {
|
||||
if (S.view === view) setMain(el("div", { class: "empty", text: `${name}: ${e.message}` }));
|
||||
return;
|
||||
}
|
||||
if (S.view !== view) return;
|
||||
|
||||
const toolbar = el("div", { class: "toolbar" });
|
||||
if (desc.svg) toolbar.append(el("a", { class: "btn primary", href: `#/svg/${encodeURIComponent(name)}`, style: "display:inline-flex;align-items:center;text-decoration:none" }, "Panel"));
|
||||
const visible = desc.rows.filter((r) => !r.hidden);
|
||||
const hidden = desc.rows.filter((r) => r.hidden);
|
||||
const list = el("div", { class: "list" }, visible.map((r) => buildRow(view, r)));
|
||||
const parts = [];
|
||||
if (toolbar.childElementCount) parts.push(toolbar);
|
||||
if (desc.doc) parts.push(el("p", { class: "doc", text: desc.doc }));
|
||||
parts.push(visible.length ? list : el("div", { class: "empty", text: "no display items" }));
|
||||
if (hidden.length) {
|
||||
const hiddenList = el("div", { class: "list" });
|
||||
const details = el("details", { class: "hidden-items" }, el("summary", { text: `${hidden.length} more items` }), hiddenList);
|
||||
details.addEventListener("toggle", () => {
|
||||
if (details.open && !hiddenList.childElementCount) {
|
||||
hiddenList.append(...hidden.map((r) => buildRow(view, r)));
|
||||
subscribe(view, hidden);
|
||||
}
|
||||
});
|
||||
parts.push(details);
|
||||
}
|
||||
setMain(...parts);
|
||||
subscribe(view, visible);
|
||||
view.timers.push(setInterval(() => refreshAges(view), 1000));
|
||||
}
|
||||
|
||||
function subscribe(view, rows) {
|
||||
const names = rows.filter((r) => r.kind !== "assembly" && r.kind !== "trigger").map((r) => r.name);
|
||||
if (!names.length) return;
|
||||
view.subscribed.push(...names);
|
||||
request("subscribe", { names }).catch((e) => toast(`subscribe failed: ${e.message}`, true));
|
||||
}
|
||||
|
||||
function buildRow(view, row) {
|
||||
const refs = { row, value: null, last: null, readState: "waiting", writing: false, ctlBuilt: false, step: null };
|
||||
const node = el("div", { class: "row" });
|
||||
if (row.group) node.style.borderLeftColor = row.group;
|
||||
refs.node = node;
|
||||
|
||||
if (row.kind === "assembly") {
|
||||
node.append(
|
||||
el("div", { class: "label" }, el("a", { href: `#/d/${encodeURIComponent(row.name)}`, text: `${row.label} ›` })),
|
||||
);
|
||||
return node;
|
||||
}
|
||||
if (row.kind === "trigger") {
|
||||
const btn = el("button", { class: "btn", text: row.button, title: row.doc || "", disabled: !row.writable,
|
||||
onclick: () => confirmDialog(`Trigger ${row.name}?`, row.doc || "", () =>
|
||||
request("trigger", { name: row.name }).catch((e) => toast(e.message, true))) });
|
||||
refs.dot = el("span", { class: "dot", text: "●", style: "color:var(--wait)" });
|
||||
node.append(el("div", { class: "label", text: row.label }), el("div", { class: "value" }), el("div", { class: "ctl" }, refs.dot, btn));
|
||||
view.rows.set(row.name, refs);
|
||||
return node;
|
||||
}
|
||||
refs.dot = el("span", { class: "dot", text: "●", style: `color:${DOT.waiting}`, title: "waiting for the first value" });
|
||||
refs.valueEl = el("div", { class: "value", text: "…" });
|
||||
refs.ctl = el("div", { class: "ctl" }, refs.dot);
|
||||
node.append(el("div", { class: "label", text: row.label }), refs.valueEl, refs.ctl);
|
||||
view.rows.set(row.name, refs);
|
||||
return node;
|
||||
}
|
||||
|
||||
function applyValue(name, value) {
|
||||
const refs = S.view?.rows.get(name);
|
||||
if (!refs || !refs.valueEl) return;
|
||||
refs.t = value.t;
|
||||
if (value.error !== undefined) {
|
||||
refs.readState = "error";
|
||||
refs.readMessage = value.error;
|
||||
refs.valueEl.className = "value error";
|
||||
refs.valueEl.textContent = value.error;
|
||||
} else {
|
||||
refs.value = value;
|
||||
refs.readState = value.state || "polled";
|
||||
refs.readMessage = "";
|
||||
const text = typeof value.num === "number" ? formatNum(value.num) : value.text;
|
||||
refs.valueEl.className = "value" + (value.cls ? ` ${value.cls}` : "") + (refs.row.writable ? " settable" : "");
|
||||
refs.valueEl.replaceChildren(text, refs.row.unit ? el("span", { class: "unit", text: refs.row.unit }) : "", el("span", { class: "age" }));
|
||||
if (!refs.ctlBuilt) buildControls(refs);
|
||||
if (refs.select && !refs.select.matches(":focus")) refs.select.value = value.text;
|
||||
}
|
||||
if (!refs.writing) showDot(refs, refs.readState, refs.readMessage);
|
||||
}
|
||||
|
||||
function showDot(refs, state, message) {
|
||||
if (!refs.dot) return;
|
||||
refs.dot.style.color = DOT[state] || DOT.error;
|
||||
refs.dot.title = message ? `${state}: ${message}` : state;
|
||||
}
|
||||
|
||||
function applyWrite({ name, state, message }) {
|
||||
const refs = S.view?.rows.get(name);
|
||||
if (state === "error") toast(`${name}: ${message}`, true);
|
||||
if (!refs) return;
|
||||
refs.writing = state === "busy" || state === "moving";
|
||||
if (refs.writing || state === "error") showDot(refs, state, message);
|
||||
else showDot(refs, refs.readState, refs.readMessage);
|
||||
}
|
||||
|
||||
function refreshAges(view) {
|
||||
const now = serverNow();
|
||||
for (const refs of view.rows.values()) {
|
||||
if (!refs.t || !refs.valueEl) continue;
|
||||
const age = now - refs.t;
|
||||
refs.valueEl.classList.toggle("stale", age > STALE_AFTER);
|
||||
const ageEl = refs.valueEl.querySelector(".age");
|
||||
if (ageEl) ageEl.textContent = age > SHOW_AGE_AFTER ? `${Math.round(age)} s ago` : "";
|
||||
}
|
||||
}
|
||||
|
||||
// ---- controls for writable items ---------------------------------------------------------------
|
||||
|
||||
function buildControls(refs) {
|
||||
refs.ctlBuilt = true;
|
||||
const { row, value } = refs;
|
||||
if (!row.writable || row.kind !== "adjustable") return;
|
||||
const name = row.name;
|
||||
const labels = row.enum || value.enum;
|
||||
if (labels) {
|
||||
refs.select = el("select", { class: "enum", "aria-label": `set ${row.label}`,
|
||||
onchange: (e) => request("set", { name, value: e.target.value }).catch((err) => toast(err.message, true)) },
|
||||
labels.map((l) => el("option", { value: l, text: l })));
|
||||
refs.select.value = value.text;
|
||||
refs.ctl.append(refs.select);
|
||||
} else if (typeof value.num === "number") {
|
||||
refs.step = el("input", { class: "step", type: "number", inputmode: "decimal", step: "any", "aria-label": "step", value: "1" });
|
||||
request("step_size", { name }).then((r) => (refs.step.value = r.step)).catch(() => {});
|
||||
const move = (sign) => request("step", { name, sign, step: parseFloat(refs.step.value) }).catch((e) => toast(e.message, true));
|
||||
refs.ctl.append(
|
||||
el("button", { class: "btn", text: "▼", "aria-label": "step down", onclick: () => move(-1) }),
|
||||
refs.step,
|
||||
el("button", { class: "btn", text: "▲", "aria-label": "step up", onclick: () => move(1) }),
|
||||
);
|
||||
}
|
||||
refs.ctl.append(el("button", { class: "btn stop", text: "■", title: "Stop", "aria-label": "stop",
|
||||
onclick: () => request("stop", { name }).catch((e) => toast(e.message, true)) }));
|
||||
if (!labels) {
|
||||
refs.valueEl.addEventListener("click", () => {
|
||||
const current = refs.value ? (typeof refs.value.num === "number" ? String(refs.value.num) : refs.value.text) : "";
|
||||
inputDialog(`Move ${name}`, `currently ${current}${row.unit ? " " + row.unit : ""}`, current, (target) =>
|
||||
request("set", { name, value: target }).catch((e) => toast(e.message, true)));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function inputDialog(title, note, initial, onOk) {
|
||||
const input = el("input", { value: initial, inputmode: "decimal", autocomplete: "off" });
|
||||
const dialog = el("dialog", {},
|
||||
el("h2", { text: title }), el("p", { text: note }), input,
|
||||
el("div", { class: "actions" },
|
||||
el("button", { class: "btn", text: "Cancel", onclick: () => dialog.close() }),
|
||||
el("button", { class: "btn primary", text: "Move", onclick: () => { dialog.close(); onOk(input.value); } })));
|
||||
input.addEventListener("keydown", (e) => { if (e.key === "Enter") { dialog.close(); onOk(input.value); } });
|
||||
dialog.addEventListener("close", () => dialog.remove());
|
||||
document.body.append(dialog);
|
||||
dialog.showModal();
|
||||
input.select();
|
||||
}
|
||||
|
||||
function confirmDialog(title, note, onOk) {
|
||||
const dialog = el("dialog", {},
|
||||
el("h2", { text: title }), note ? el("p", { text: note }) : null,
|
||||
el("div", { class: "actions" },
|
||||
el("button", { class: "btn", text: "Cancel", onclick: () => dialog.close() }),
|
||||
el("button", { class: "btn primary", text: "OK", onclick: () => { dialog.close(); onOk(); } })));
|
||||
dialog.addEventListener("close", () => dialog.remove());
|
||||
document.body.append(dialog);
|
||||
dialog.showModal();
|
||||
}
|
||||
|
||||
// ---- SVG panels ------------------------------------------------------------------------------------
|
||||
|
||||
const NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/;
|
||||
|
||||
function sanitizeSvg(text) {
|
||||
// Parse, drop anything executable, keep the eco click markers as data-eco.
|
||||
// onclick="// eco: <name>" (or a <desc> child) is how eco's panels mark a
|
||||
// device; here a click only opens that device's view -- nothing runs.
|
||||
const doc = new DOMParser().parseFromString(text, "image/svg+xml");
|
||||
const svg = doc.documentElement;
|
||||
if (svg.nodeName !== "svg" || doc.getElementsByTagName("parsererror").length) throw new Error("not an SVG");
|
||||
svg.querySelectorAll("script, foreignObject, iframe, object, embed").forEach((n) => n.remove());
|
||||
for (const node of [svg, ...svg.querySelectorAll("*")]) {
|
||||
const onclick = node.getAttribute("onclick");
|
||||
const marker = onclick && onclick.match(/^\s*\/\/\s*eco:\s*(.*)$/);
|
||||
if (marker) node.setAttribute("data-eco", marker[1].trim());
|
||||
else if (node !== svg && node.nodeName === "g") {
|
||||
const desc = [...node.children].find((c) => c.nodeName === "desc");
|
||||
if (desc && NAME_RE.test(desc.textContent.trim())) node.setAttribute("data-eco", desc.textContent.trim());
|
||||
}
|
||||
for (const attr of [...node.attributes]) {
|
||||
if (/^on/i.test(attr.name) || (/href$/i.test(attr.name) && /^\s*javascript:/i.test(attr.value))) node.removeAttribute(attr.name);
|
||||
}
|
||||
}
|
||||
if (!svg.getAttribute("viewBox") && svg.getAttribute("width") && svg.getAttribute("height")) {
|
||||
svg.setAttribute("viewBox", `0 0 ${parseFloat(svg.getAttribute("width"))} ${parseFloat(svg.getAttribute("height"))}`);
|
||||
}
|
||||
svg.removeAttribute("width");
|
||||
svg.removeAttribute("height");
|
||||
return document.importNode(svg, true);
|
||||
}
|
||||
|
||||
async function showSvg(name) {
|
||||
const view = newView("svg", name);
|
||||
setTitle(`${name} panel`, true);
|
||||
const panel = el("div", { class: "panel" });
|
||||
const note = el("p", { class: "panel-note", text: "loading…" });
|
||||
setMain(panel, note);
|
||||
let prefix = name;
|
||||
let busy = false;
|
||||
|
||||
const load = async () => {
|
||||
if (busy || document.visibilityState !== "visible") return;
|
||||
busy = true;
|
||||
try {
|
||||
const response = await fetch(`/api/svg?name=${encodeURIComponent(name)}`, { cache: "no-store" });
|
||||
if (!response.ok) throw new Error(response.statusText || `HTTP ${response.status}`);
|
||||
prefix = response.headers.get("X-Eco-Prefix") || name;
|
||||
const svg = sanitizeSvg(await response.text());
|
||||
if (S.view !== view) return;
|
||||
panel.replaceChildren(svg);
|
||||
note.textContent = `live – refreshed every ${SVG_REFRESH / 1000} s · tap a device to open it`;
|
||||
} catch (e) {
|
||||
if (S.view === view) note.textContent = `could not load the panel: ${e.message}`;
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
};
|
||||
panel.addEventListener("click", (e) => {
|
||||
const target = e.target.closest("[data-eco]");
|
||||
if (!target) return;
|
||||
const raw = target.getAttribute("data-eco");
|
||||
if (!NAME_RE.test(raw)) return toast(`not a device name: ${raw}`, true);
|
||||
location.hash = `#/d/${encodeURIComponent(prefix ? `${prefix}.${raw}` : raw)}`;
|
||||
});
|
||||
await load();
|
||||
view.timers.push(setInterval(load, SVG_REFRESH));
|
||||
}
|
||||
|
||||
// ---- start ---------------------------------------------------------------------------------------------
|
||||
|
||||
if ("serviceWorker" in navigator && window.isSecureContext) {
|
||||
navigator.serviceWorker.register("/sw.js").catch(() => {});
|
||||
}
|
||||
connect();
|
||||
@@ -0,0 +1,6 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||
<rect width="512" height="512" rx="96" fill="#1d3557"/>
|
||||
<circle cx="256" cy="256" r="150" fill="none" stroke="#a8dadc" stroke-width="28"/>
|
||||
<circle cx="256" cy="256" r="58" fill="#e63946"/>
|
||||
<line x1="40" y1="256" x2="472" y2="256" stroke="#f1faee" stroke-width="14" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 368 B |
@@ -0,0 +1,25 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<meta name="theme-color" content="#1d3557">
|
||||
<title>eco</title>
|
||||
<link rel="manifest" href="/manifest.webmanifest">
|
||||
<link rel="icon" href="/icon.svg" type="image/svg+xml">
|
||||
<link rel="apple-touch-icon" href="/icon.svg">
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<header id="bar">
|
||||
<button id="back" class="icon" aria-label="Back" hidden>‹</button>
|
||||
<h1 id="title">eco</h1>
|
||||
<span id="mode" class="badge"></span>
|
||||
<span id="conn" class="conn" title="connecting">●</span>
|
||||
</header>
|
||||
<div id="banner" hidden></div>
|
||||
<main id="main"></main>
|
||||
<div id="toast" hidden></div>
|
||||
<script type="module" src="/static/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "eco",
|
||||
"short_name": "eco",
|
||||
"description": "eco beamline control - web client",
|
||||
"start_url": "/",
|
||||
"scope": "/",
|
||||
"display": "standalone",
|
||||
"background_color": "#f4f5f7",
|
||||
"theme_color": "#1d3557",
|
||||
"icons": [
|
||||
{"src": "/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any maskable"}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
:root {
|
||||
--bg: #f4f5f7;
|
||||
--surface: #ffffff;
|
||||
--text: #1b1f24;
|
||||
--muted: #667085;
|
||||
--line: #e2e5ea;
|
||||
--accent: #1d3557;
|
||||
--accent-text: #ffffff;
|
||||
--link: #1f5fbf;
|
||||
--ok: #2e9d4a;
|
||||
--polled: #3d7fd9;
|
||||
--busy: #f0a020;
|
||||
--err: #d93025;
|
||||
--wait: #9e9e9e;
|
||||
--green: #2e7d32;
|
||||
--red: #c62828;
|
||||
--tap: 44px;
|
||||
color-scheme: light;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root:not([data-theme="light"]) {
|
||||
--bg: #121418;
|
||||
--surface: #1c1f25;
|
||||
--text: #e7e9ee;
|
||||
--muted: #9aa3b2;
|
||||
--line: #2c313a;
|
||||
--accent: #24426e;
|
||||
--link: #8ab4ff;
|
||||
--green: #5cc46b;
|
||||
--red: #ff6b61;
|
||||
color-scheme: dark;
|
||||
}
|
||||
}
|
||||
:root[data-theme="dark"] {
|
||||
--bg: #121418; --surface: #1c1f25; --text: #e7e9ee; --muted: #9aa3b2; --line: #2c313a;
|
||||
--accent: #24426e; --link: #8ab4ff; --green: #5cc46b; --red: #ff6b61; color-scheme: dark;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html, body { margin: 0; background: var(--bg); color: var(--text);
|
||||
font: 16px/1.4 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
|
||||
body { padding-bottom: env(safe-area-inset-bottom); }
|
||||
button, input, select { font: inherit; color: inherit; }
|
||||
|
||||
#bar { position: sticky; top: 0; z-index: 5; display: flex; align-items: center; gap: 8px;
|
||||
padding: calc(6px + env(safe-area-inset-top)) 12px 6px; background: var(--accent); color: var(--accent-text); }
|
||||
#bar h1 { flex: 1; margin: 0; font-size: 18px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
#bar .icon { min-width: var(--tap); height: var(--tap); border: 0; background: none; color: inherit; font-size: 30px; line-height: 1; cursor: pointer; }
|
||||
.badge { font-size: 12px; padding: 2px 8px; border-radius: 10px; background: rgba(255,255,255,.18); white-space: nowrap; }
|
||||
.badge.writes { background: var(--busy); color: #000; }
|
||||
.conn { font-size: 18px; color: var(--wait); }
|
||||
.conn.up { color: var(--ok); }
|
||||
.conn.down { color: var(--err); }
|
||||
|
||||
#banner { padding: 8px 16px; background: var(--err); color: #fff; font-size: 14px; }
|
||||
#main { max-width: 900px; margin: 0 auto; padding: 12px 16px 40px; }
|
||||
|
||||
.search { width: 100%; height: var(--tap); padding: 0 12px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface); margin-bottom: 12px; }
|
||||
.section-title { margin: 16px 4px 6px; font-size: 13px; text-transform: uppercase; letter-spacing: .05em; color: var(--muted); }
|
||||
.list { background: var(--surface); border: 1px solid var(--line); border-radius: 12px; overflow: hidden; }
|
||||
.list > * + * { border-top: 1px solid var(--line); }
|
||||
.item { display: flex; align-items: center; gap: 10px; min-height: var(--tap); padding: 8px 12px; cursor: pointer; text-decoration: none; color: inherit; }
|
||||
.item:active { background: var(--line); }
|
||||
.item .name { flex: 1 0 auto; max-width: 70%; font-weight: 500; overflow-wrap: anywhere; }
|
||||
.item .note { flex: 0 1 auto; margin-left: auto; color: var(--muted); font-size: 13px; text-align: right; overflow-wrap: anywhere; }
|
||||
.item.failed .name { color: var(--red); }
|
||||
.item.lazy .name { color: var(--muted); }
|
||||
|
||||
.row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; padding: 8px 12px; border-left: 4px solid transparent; }
|
||||
.row .label { flex: 1 1 140px; min-width: 110px; font-weight: 500; word-break: break-all; }
|
||||
.row .label a { color: var(--link); text-decoration: none; }
|
||||
.row .value { flex: 1 1 120px; min-width: 90px; font-variant-numeric: tabular-nums; word-break: break-all; }
|
||||
.row .value.green { color: var(--green); font-weight: 600; }
|
||||
.row .value.red { color: var(--red); font-weight: 600; }
|
||||
.row .value.stale { opacity: .45; }
|
||||
.row .value .unit { color: var(--muted); font-size: 13px; margin-left: 3px; }
|
||||
.row .value .age { color: var(--muted); font-size: 12px; margin-left: 6px; }
|
||||
.row .value.error { color: var(--err); font-size: 13px; }
|
||||
.row .ctl { display: flex; align-items: center; gap: 6px; flex: 0 1 auto; }
|
||||
.dot { font-size: 14px; color: var(--wait); cursor: help; }
|
||||
|
||||
.btn { min-width: var(--tap); height: var(--tap); padding: 0 10px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface); cursor: pointer; touch-action: manipulation; }
|
||||
.btn:active { background: var(--line); }
|
||||
.btn:disabled { opacity: .45; cursor: default; }
|
||||
.btn.stop { color: var(--err); font-weight: 700; }
|
||||
.btn.primary { background: var(--accent); color: var(--accent-text); border-color: var(--accent); }
|
||||
.step { width: 76px; height: var(--tap); padding: 0 6px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface); text-align: right; }
|
||||
select.enum { height: var(--tap); border: 1px solid var(--line); border-radius: 10px; background: var(--surface); padding: 0 8px; max-width: 180px; }
|
||||
.value.settable { text-decoration: underline dotted; cursor: pointer; }
|
||||
|
||||
.toolbar { display: flex; gap: 8px; flex-wrap: wrap; margin: 4px 0 12px; }
|
||||
.doc { color: var(--muted); font-size: 14px; margin: 0 4px 12px; }
|
||||
.empty, .loading { color: var(--muted); padding: 24px 4px; text-align: center; }
|
||||
details.hidden-items { margin-top: 12px; }
|
||||
details.hidden-items summary { cursor: pointer; color: var(--muted); padding: 8px 4px; min-height: var(--tap); }
|
||||
|
||||
.panel { background: #fff; border: 1px solid var(--line); border-radius: 12px; overflow: auto; touch-action: pan-x pan-y pinch-zoom; }
|
||||
.panel svg { display: block; width: 100%; height: auto; }
|
||||
.panel [data-eco] { cursor: pointer; }
|
||||
.panel-note { color: var(--muted); font-size: 13px; margin: 6px 4px; }
|
||||
|
||||
#toast { position: fixed; left: 16px; right: 16px; bottom: calc(16px + env(safe-area-inset-bottom)); z-index: 10;
|
||||
max-width: 600px; margin: 0 auto; padding: 12px 14px; border-radius: 12px; background: #222; color: #fff; font-size: 14px; box-shadow: 0 4px 18px rgba(0,0,0,.3); }
|
||||
#toast.err { background: var(--err); }
|
||||
|
||||
dialog { border: 1px solid var(--line); border-radius: 14px; background: var(--surface); color: var(--text); width: min(420px, calc(100vw - 32px)); padding: 16px; }
|
||||
dialog::backdrop { background: rgba(0,0,0,.4); }
|
||||
dialog h2 { margin: 0 0 6px; font-size: 17px; }
|
||||
dialog p { margin: 0 0 12px; color: var(--muted); font-size: 14px; word-break: break-all; }
|
||||
dialog input { width: 100%; height: var(--tap); padding: 0 10px; border: 1px solid var(--line); border-radius: 10px; background: var(--bg); margin-bottom: 12px; }
|
||||
dialog .actions { display: flex; justify-content: flex-end; gap: 8px; }
|
||||
@@ -0,0 +1,36 @@
|
||||
// eco web service worker: caches the app shell only, so the installed app
|
||||
// opens (and shows "disconnected") without a connection. Never caches values,
|
||||
// SVG panels or the websocket -- a stale beamline value shown as current
|
||||
// would be worse than none. Network first, so a new client version is
|
||||
// picked up as soon as the gateway is reachable.
|
||||
const CACHE = "eco-shell-v1";
|
||||
const SHELL = ["/", "/static/app.js", "/static/style.css", "/icon.svg", "/manifest.webmanifest"];
|
||||
|
||||
self.addEventListener("install", (event) => {
|
||||
event.waitUntil(caches.open(CACHE).then((c) => c.addAll(SHELL)).catch(() => {}));
|
||||
self.skipWaiting();
|
||||
});
|
||||
|
||||
self.addEventListener("activate", (event) => {
|
||||
event.waitUntil(
|
||||
caches.keys().then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))))
|
||||
);
|
||||
self.clients.claim();
|
||||
});
|
||||
|
||||
self.addEventListener("fetch", (event) => {
|
||||
const url = new URL(event.request.url);
|
||||
if (event.request.method !== "GET" || url.origin !== location.origin) return;
|
||||
if (!SHELL.includes(url.pathname)) return; // /api, /ws, ...: straight to the network
|
||||
event.respondWith(
|
||||
fetch(event.request)
|
||||
.then((response) => {
|
||||
if (response.ok) {
|
||||
const copy = response.clone();
|
||||
caches.open(CACHE).then((c) => c.put(event.request, copy));
|
||||
}
|
||||
return response;
|
||||
})
|
||||
.catch(() => caches.match(event.request))
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,238 @@
|
||||
"""What the web client is told about eco objects and values -- plain,
|
||||
JSON-serializable data, no tornado and no GUI imports (so it is unit-tested
|
||||
on its own, see tests/test_web_viewmodels.py).
|
||||
|
||||
Mirrors what the property grids show (eco.widgets.display_widget /
|
||||
display_qt): the rows are an assembly's display collection, everything else
|
||||
in its status collection is "hidden"; the group colours come from the same
|
||||
`section_row_styles` the terminal table uses; the value text from
|
||||
live_values.format_value. Kept as a small parallel implementation on purpose
|
||||
rather than importing display_widget (ipywidgets) -- see web_frontend/
|
||||
ARCHITECTURE.md on keeping the front-ends independent.
|
||||
"""
|
||||
import enum
|
||||
import math
|
||||
import numbers
|
||||
|
||||
from eco.widgets.live_values import format_value
|
||||
|
||||
MAX_TEXT = 300 # characters of a value's text sent to the client (arrays, long strings)
|
||||
|
||||
|
||||
# -- values ----------------------------------------------------------------------------
|
||||
|
||||
|
||||
def encode_value(value):
|
||||
"""One readback as sent to the client: always a "text"; "num" for a
|
||||
finite real number (what the ▲/▼ buttons step from), "bool" for a bool,
|
||||
"enum" (the labels) for an enum, "cls" "green"/"red" for open/closed."""
|
||||
out = {"text": _clip(format_value(value))}
|
||||
if isinstance(value, enum.Enum):
|
||||
out["enum"] = [member.name for member in type(value)]
|
||||
elif isinstance(value, bool) or getattr(getattr(value, "dtype", None), "kind", None) == "b":
|
||||
out["bool"] = bool(value)
|
||||
elif isinstance(value, numbers.Real):
|
||||
try:
|
||||
number = float(value)
|
||||
except Exception:
|
||||
number = None
|
||||
if number is not None and math.isfinite(number):
|
||||
out["num"] = int(value) if isinstance(value, numbers.Integral) else number
|
||||
cls = state_class(value)
|
||||
if cls:
|
||||
out["cls"] = cls
|
||||
return out
|
||||
|
||||
|
||||
def state_class(value):
|
||||
""""green"/"red" for the open/closed convention the grids colour
|
||||
(eco.widgets.display_widget._state_css_class), else None. The grids'
|
||||
second rule -- EPICS alarm severity -- needs an extra CA read per
|
||||
update and is left out here for now."""
|
||||
if isinstance(value, enum.Enum):
|
||||
value = value.name
|
||||
if isinstance(value, str):
|
||||
low = value.strip().lower()
|
||||
if low == "open":
|
||||
return "green"
|
||||
if low == "closed":
|
||||
return "red"
|
||||
return None
|
||||
|
||||
|
||||
def coerce_target(text_or_value, last_value):
|
||||
"""A target sent by the client, converted to the type of the item's
|
||||
last readback (the grids do the same through their typed input
|
||||
widgets): an enum takes its label, numbers are parsed, bools accept
|
||||
true/false/1/0."""
|
||||
value = text_or_value
|
||||
if isinstance(last_value, enum.Enum):
|
||||
return str(value)
|
||||
if isinstance(last_value, bool):
|
||||
if isinstance(value, str):
|
||||
low = value.strip().lower()
|
||||
if low in ("true", "1", "yes", "on"):
|
||||
return True
|
||||
if low in ("false", "0", "no", "off"):
|
||||
return False
|
||||
raise ValueError(f"not a boolean: {value!r}")
|
||||
return bool(value)
|
||||
if isinstance(last_value, numbers.Integral):
|
||||
number = float(value)
|
||||
if not number.is_integer():
|
||||
raise ValueError(f"not an integer: {value!r}")
|
||||
return int(number)
|
||||
if isinstance(last_value, numbers.Real):
|
||||
return float(value)
|
||||
return value
|
||||
|
||||
|
||||
def _clip(text):
|
||||
return text if len(text) <= MAX_TEXT else text[: MAX_TEXT - 1] + "…"
|
||||
|
||||
|
||||
# -- objects ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def kind_of(obj):
|
||||
""""trigger" | "assembly" | "adjustable" | "detector" | "other"."""
|
||||
from eco.elements.adjustable import AdjustableTrigger
|
||||
from eco.elements.assembly import Assembly
|
||||
from eco.elements.protocols import Adjustable, Detector
|
||||
|
||||
if isinstance(obj, AdjustableTrigger):
|
||||
return "trigger"
|
||||
if isinstance(obj, Assembly):
|
||||
return "assembly"
|
||||
if isinstance(obj, Adjustable):
|
||||
return "adjustable"
|
||||
if isinstance(obj, Detector):
|
||||
return "detector"
|
||||
return "other"
|
||||
|
||||
|
||||
def full_name(obj, fallback=None):
|
||||
try:
|
||||
return obj.alias.get_full_name()
|
||||
except Exception:
|
||||
return fallback if fallback is not None else getattr(obj, "name", None) or str(obj)
|
||||
|
||||
|
||||
def relative_name(obj, base):
|
||||
try:
|
||||
return obj.alias.get_full_name(base=base)
|
||||
except Exception:
|
||||
return getattr(obj, "name", None) or str(obj)
|
||||
|
||||
|
||||
def enum_labels(obj):
|
||||
"""Enum labels an item declares itself (AdjustablePvEnum etc.); items
|
||||
whose enum only shows in the value report them with each value
|
||||
(encode_value's "enum")."""
|
||||
strs = getattr(obj, "enum_strs", None)
|
||||
if strs:
|
||||
try:
|
||||
return [str(s) for s in strs]
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def has_svg_panel(obj):
|
||||
"""Whether `obj` can show an SVG panel (Assembly.show's two ways: a
|
||||
`_widget_svg_panel` builder or a fixed `_show_svg` file). Looked up
|
||||
without attribute access on the instance, which for an Assembly can
|
||||
have side effects."""
|
||||
if callable(getattr(type(obj), "_widget_svg_panel", None)):
|
||||
return True
|
||||
try:
|
||||
return bool(object.__getattribute__(obj, "__dict__").get("_show_svg"))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _display_and_all(assembly):
|
||||
try:
|
||||
display_items = list(assembly.display_collection())
|
||||
except Exception:
|
||||
try:
|
||||
display_items = list(assembly.status_collection.get_list(selection="display"))
|
||||
except Exception:
|
||||
display_items = []
|
||||
try:
|
||||
all_items = list(assembly.status_collection.get_list())
|
||||
except Exception:
|
||||
all_items = []
|
||||
hidden = [item for item in all_items if not any(item is d for d in display_items)]
|
||||
return display_items, hidden
|
||||
|
||||
|
||||
def _group_colors(relative_names):
|
||||
from eco.utilities.tables import section_row_styles
|
||||
|
||||
styles = section_row_styles([n.split(".", 1)[0] for n in relative_names])
|
||||
colors = []
|
||||
for style in styles:
|
||||
if style and style.startswith("on #"):
|
||||
colors.append(style[3:])
|
||||
elif style == "on grey30":
|
||||
colors.append("#4d4d4d")
|
||||
else:
|
||||
colors.append(None)
|
||||
return colors
|
||||
|
||||
|
||||
def row_for(item, base=None):
|
||||
kind = kind_of(item)
|
||||
row = {
|
||||
"name": full_name(item),
|
||||
"label": relative_name(item, base) if base is not None else full_name(item),
|
||||
"kind": kind,
|
||||
"writable": kind in ("adjustable", "trigger"),
|
||||
}
|
||||
labels = enum_labels(item) if kind in ("adjustable", "detector") else None
|
||||
if labels:
|
||||
row["enum"] = labels
|
||||
unit = getattr(item, "unit", None)
|
||||
try:
|
||||
unit = unit.get_current_value() if hasattr(unit, "get_current_value") else unit
|
||||
except Exception:
|
||||
unit = None
|
||||
if isinstance(unit, str) and unit:
|
||||
row["unit"] = unit
|
||||
if kind == "trigger":
|
||||
row["button"] = getattr(item, "button_label", None) or "▶ Trigger"
|
||||
doc = getattr(item, "doc", None)
|
||||
if doc:
|
||||
row["doc"] = str(doc)
|
||||
if kind == "assembly":
|
||||
row["svg"] = has_svg_panel(item)
|
||||
return row
|
||||
|
||||
|
||||
def describe(obj, name=None):
|
||||
"""(view, objects): the description of `obj` the client renders, and
|
||||
{row name: object} for every row in it -- the session keeps the latter
|
||||
so later requests address rows by name without re-resolving them."""
|
||||
name = name or full_name(obj)
|
||||
kind = kind_of(obj)
|
||||
view = {"name": name, "title": full_name(obj, name), "kind": kind, "svg": has_svg_panel(obj)}
|
||||
objects = {}
|
||||
if kind == "assembly":
|
||||
display_items, hidden_items = _display_and_all(obj)
|
||||
rows = [row_for(item, base=obj) for item in display_items]
|
||||
for row, color in zip(rows, _group_colors([r["label"] for r in rows])):
|
||||
if color:
|
||||
row["group"] = color
|
||||
hidden = [dict(row_for(item, base=obj), hidden=True) for item in hidden_items]
|
||||
view["rows"] = rows + hidden
|
||||
for item, row in zip(display_items + hidden_items, view["rows"]):
|
||||
objects[row["name"]] = item
|
||||
else:
|
||||
row = row_for(obj)
|
||||
view["rows"] = [row]
|
||||
objects[row["name"]] = obj
|
||||
doc = (getattr(type(obj), "__doc__", None) or "").strip()
|
||||
if doc:
|
||||
view["doc"] = doc.split("\n\n", 1)[0][:500]
|
||||
return view, objects
|
||||
@@ -0,0 +1,177 @@
|
||||
"""eco.web.client_session: the protocol, without a transport -- requests
|
||||
answered off the caller's thread, coalesced values, writes only when
|
||||
enabled, Stop during a move."""
|
||||
import queue
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from eco.web.backends import SessionBackend
|
||||
from eco.web.client_session import ClientSession
|
||||
from eco.web.demo import DemoNamespace
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self, writes=False):
|
||||
self.messages = queue.Queue()
|
||||
self.session = ClientSession(SessionBackend(DemoNamespace()), self.messages.put,
|
||||
writes=writes, poll_interval=0.05)
|
||||
self.next_id = 0
|
||||
self.backlog = [] # events that arrived while waiting for a reply
|
||||
|
||||
def call(self, op, timeout=5.0, **args):
|
||||
self.next_id += 1
|
||||
request_id = self.next_id
|
||||
self.session.handle({"v": 0, "id": request_id, "op": op, "args": args})
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
message = self.messages.get(timeout=timeout)
|
||||
if message.get("re") == request_id:
|
||||
return message
|
||||
if "ev" in message:
|
||||
self.backlog.append(message)
|
||||
raise AssertionError(f"no reply to {op}")
|
||||
|
||||
def events(self, kind, seconds=1.0):
|
||||
found = [m["data"] for m in self.backlog if m["ev"] == kind]
|
||||
self.backlog = [m for m in self.backlog if m["ev"] != kind]
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
message = self.messages.get(timeout=0.05)
|
||||
except queue.Empty:
|
||||
continue
|
||||
if message.get("ev") == kind:
|
||||
found.append(message["data"])
|
||||
return found
|
||||
|
||||
def values(self, name, seconds=2.0):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
event = self.session.flush()
|
||||
if event and name in event["data"]:
|
||||
return event["data"][name]
|
||||
time.sleep(0.02)
|
||||
raise AssertionError(f"no value for {name}")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
c = Client()
|
||||
yield c
|
||||
c.session.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def writer():
|
||||
c = Client(writes=True)
|
||||
yield c
|
||||
c.session.close()
|
||||
|
||||
|
||||
def test_hello_and_names(client):
|
||||
hello = client.call("hello", client_version="t")
|
||||
assert hello["ok"] and hello["data"]["writes"] is False and hello["data"]["label"] == "demo"
|
||||
names = client.call("names")["data"]
|
||||
assert "mono" in names["initialized"]
|
||||
|
||||
|
||||
def test_unknown_op_and_bad_arguments_are_errors(client):
|
||||
reply = client.call("frobnicate")
|
||||
assert not reply["ok"] and reply["error"]["type"] == "ProtocolError"
|
||||
reply = client.call("describe", nonsense=1)
|
||||
assert not reply["ok"] and reply["error"]["type"] == "ProtocolError"
|
||||
|
||||
|
||||
def test_subscribe_needs_a_described_name(client):
|
||||
reply = client.call("subscribe", names=["mono.energy"])
|
||||
assert not reply["ok"] and reply["error"]["type"] == "NotFound"
|
||||
|
||||
|
||||
def test_values_arrive_coalesced_after_subscribe(client):
|
||||
client.call("describe", name="mono")
|
||||
assert client.call("subscribe", names=["mono.energy", "mono.pitch_rbv"])["ok"]
|
||||
value = client.values("mono.energy")
|
||||
assert value["num"] == 7.0 and value["state"] == "polled" and value["t"] > 0
|
||||
time.sleep(0.3) # several polls at 0.05 s ...
|
||||
event = client.session.flush()
|
||||
assert event["ev"] == "values" and "now" in event
|
||||
assert set(event["data"]) <= {"mono.energy", "mono.pitch_rbv"} # ... one entry each
|
||||
|
||||
|
||||
def test_unsubscribed_items_stop_reporting(client):
|
||||
client.call("describe", name="mono")
|
||||
client.call("subscribe", names=["mono.pitch_rbv"])
|
||||
client.values("mono.pitch_rbv")
|
||||
client.call("unsubscribe", names=["mono.pitch_rbv"])
|
||||
time.sleep(0.2)
|
||||
client.session.flush()
|
||||
time.sleep(0.3)
|
||||
event = client.session.flush()
|
||||
assert event is None or "mono.pitch_rbv" not in event["data"]
|
||||
|
||||
|
||||
def test_writes_are_refused_by_default(client):
|
||||
client.call("describe", name="mono")
|
||||
for op, args in [("set", {"value": 8}), ("step", {"sign": 1, "step": 0.1}), ("stop", {}), ("trigger", {})]:
|
||||
name = "mono.home_all" if op == "trigger" else "mono.energy"
|
||||
reply = client.call(op, name=name, **args)
|
||||
assert not reply["ok"] and reply["error"]["type"] == "WritesDisabled", op
|
||||
rows = client.call("describe", name="mono")["data"]["rows"]
|
||||
assert not any(r["writable"] for r in rows)
|
||||
|
||||
|
||||
def test_set_reports_moving_then_done(writer):
|
||||
writer.call("describe", name="lxt")
|
||||
writer.call("subscribe", names=["lxt"])
|
||||
writer.values("lxt")
|
||||
assert writer.call("set", name="lxt", value="1e-13")["ok"]
|
||||
states = [e["state"] for e in writer.events("write", seconds=1.0)]
|
||||
assert states[:2] == ["busy", "moving"] and states[-1] == "idle"
|
||||
|
||||
|
||||
def test_set_errors_come_back_as_events(writer):
|
||||
writer.call("describe", name="mono")
|
||||
writer.call("subscribe", names=["mono.energy"])
|
||||
writer.values("mono.energy")
|
||||
writer.call("set", name="mono.energy", value=99) # outside the simulated limits
|
||||
errors = [e for e in writer.events("write", seconds=0.5) if e["state"] == "error"]
|
||||
assert errors and "outside limits" in errors[0]["message"]
|
||||
|
||||
|
||||
def test_stop_during_a_move(writer):
|
||||
writer.call("describe", name="slits")
|
||||
writer.call("subscribe", names=["slits.hgap"])
|
||||
writer.values("slits.hgap")
|
||||
writer.call("set", name="slits.hgap", value=9.0) # 16 s at 0.5 mm/s
|
||||
time.sleep(0.3)
|
||||
assert writer.call("stop", name="slits.hgap")["ok"]
|
||||
states = [e["state"] for e in writer.events("write", seconds=1.0)]
|
||||
assert states[-1] == "idle"
|
||||
assert writer.session._objects["slits.hgap"].get_current_value() < 2.0
|
||||
|
||||
|
||||
def test_step_and_enum_set(writer):
|
||||
writer.call("describe", name="vacuum")
|
||||
writer.call("subscribe", names=["vacuum.valve3"])
|
||||
assert writer.values("vacuum.valve3")["text"] == "closed"
|
||||
writer.call("set", name="vacuum.valve3", value="open")
|
||||
writer.events("write", seconds=1.2)
|
||||
assert writer.session._objects["vacuum.valve3"].get_current_value().name == "open"
|
||||
|
||||
writer.call("describe", name="mono")
|
||||
step = writer.call("step_size", name="mono.harmonic")["data"]["step"]
|
||||
assert step == 1
|
||||
writer.call("step", name="mono.harmonic", sign=1, step=step)
|
||||
writer.events("write", seconds=0.3)
|
||||
assert writer.session._objects["mono.harmonic"].get_current_value() == 4
|
||||
|
||||
|
||||
def test_writes_can_be_limited_to_names():
|
||||
c = Client(writes={"mono.harmonic"})
|
||||
try:
|
||||
rows = {r["name"]: r["writable"] for r in c.call("describe", name="mono")["data"]["rows"]}
|
||||
assert rows["mono.harmonic"] and not rows["mono.energy"]
|
||||
assert c.call("set", name="mono.energy", value=8)["error"]["type"] == "WritesDisabled"
|
||||
finally:
|
||||
c.session.close()
|
||||
@@ -0,0 +1,134 @@
|
||||
"""eco.web.gateway end to end: a real tornado server on an ephemeral port,
|
||||
token handling, static files, the SVG endpoint and the websocket."""
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
tornado = pytest.importorskip("tornado")
|
||||
from tornado.httpclient import AsyncHTTPClient, HTTPClientError, HTTPRequest
|
||||
from tornado.websocket import websocket_connect
|
||||
|
||||
from eco.web.backends import SessionBackend
|
||||
from eco.web.demo import DemoNamespace
|
||||
from eco.web.gateway import COOKIE, WebGateway
|
||||
|
||||
TOKEN = "test-token"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def gateway():
|
||||
gw = WebGateway(SessionBackend(DemoNamespace()), port=0, token=TOKEN).start()
|
||||
yield gw
|
||||
gw.stop()
|
||||
|
||||
|
||||
def fetch(gateway, path, **kwargs):
|
||||
async def go():
|
||||
client = AsyncHTTPClient()
|
||||
request = HTTPRequest(f"http://127.0.0.1:{gateway.port}{path}", follow_redirects=False, **kwargs)
|
||||
try:
|
||||
return await client.fetch(request, raise_error=False)
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
return asyncio.run(go())
|
||||
|
||||
|
||||
def test_index_requires_the_token(gateway):
|
||||
assert fetch(gateway, "/").code == 403
|
||||
assert fetch(gateway, "/?token=wrong").code == 403
|
||||
|
||||
|
||||
def test_token_in_url_sets_cookie_and_redirects(gateway):
|
||||
response = fetch(gateway, f"/?token={TOKEN}")
|
||||
assert response.code == 302 and response.headers["Location"] == "/"
|
||||
assert f"{COOKIE}={TOKEN}" in response.headers["Set-Cookie"]
|
||||
assert "HttpOnly" in response.headers["Set-Cookie"]
|
||||
page = fetch(gateway, "/", headers={"Cookie": f"{COOKIE}={TOKEN}"})
|
||||
assert page.code == 200 and b"/static/app.js" in page.body
|
||||
|
||||
|
||||
def test_app_shell_is_served(gateway):
|
||||
for path, kind in [("/sw.js", "javascript"), ("/manifest.webmanifest", "manifest"),
|
||||
("/icon.svg", "svg"), ("/static/app.js", "javascript"), ("/static/style.css", "css")]:
|
||||
response = fetch(gateway, path)
|
||||
assert response.code == 200, path
|
||||
assert kind in response.headers["Content-Type"], path
|
||||
|
||||
|
||||
def test_svg_endpoint(gateway):
|
||||
assert fetch(gateway, "/api/svg?name=vacuum").code == 403
|
||||
response = fetch(gateway, f"/api/svg?name=vacuum&token={TOKEN}")
|
||||
assert response.code == 200 and response.body.startswith(b"<svg")
|
||||
assert response.headers["X-Eco-Prefix"] == "vacuum"
|
||||
assert fetch(gateway, f"/api/svg?name=mono&token={TOKEN}").code == 404
|
||||
|
||||
|
||||
def test_websocket_rejects_without_token(gateway):
|
||||
async def go():
|
||||
ws = await websocket_connect(f"ws://127.0.0.1:{gateway.port}/ws")
|
||||
message = await ws.read_message()
|
||||
return message, ws.close_code
|
||||
|
||||
message, code = asyncio.run(go())
|
||||
assert message is None and code == 4403
|
||||
|
||||
|
||||
def test_websocket_round_trip_and_values(gateway):
|
||||
async def go():
|
||||
request = HTTPRequest(f"ws://127.0.0.1:{gateway.port}/ws", headers={"Cookie": f"{COOKIE}={TOKEN}"})
|
||||
ws = await websocket_connect(request)
|
||||
|
||||
async def call(i, op, **args):
|
||||
await ws.write_message(json.dumps({"v": 0, "id": i, "op": op, "args": args}))
|
||||
while True:
|
||||
message = json.loads(await asyncio.wait_for(ws.read_message(), 5))
|
||||
if message.get("re") == i:
|
||||
return message
|
||||
|
||||
hello = await call(1, "hello")
|
||||
await call(2, "describe", name="mono")
|
||||
await call(3, "subscribe", names=["mono.energy"])
|
||||
while True:
|
||||
message = json.loads(await asyncio.wait_for(ws.read_message(), 5))
|
||||
if message.get("ev") == "values" and "mono.energy" in message["data"]:
|
||||
break
|
||||
ws.close()
|
||||
return hello, message
|
||||
|
||||
hello, values = asyncio.run(go())
|
||||
assert hello["ok"] and hello["data"]["writes"] is False
|
||||
assert values["data"]["mono.energy"]["num"] == 7.0
|
||||
|
||||
|
||||
def test_stop_closes_client_connections():
|
||||
gw = WebGateway(SessionBackend(DemoNamespace()), port=0, token=TOKEN).start()
|
||||
|
||||
async def go():
|
||||
request = HTTPRequest(f"ws://127.0.0.1:{gw.port}/ws", headers={"Cookie": f"{COOKIE}={TOKEN}"})
|
||||
ws = await websocket_connect(request)
|
||||
await ws.write_message(json.dumps({"v": 0, "id": 1, "op": "ping"}))
|
||||
reply = json.loads(await asyncio.wait_for(ws.read_message(), 5))
|
||||
await asyncio.get_running_loop().run_in_executor(None, gw.stop)
|
||||
closed = await asyncio.wait_for(ws.read_message(), 5)
|
||||
return reply, closed, ws.close_code
|
||||
|
||||
reply, closed, code = asyncio.run(go())
|
||||
assert reply["ok"] and reply["data"] == {}
|
||||
assert closed is None and code == 1001
|
||||
assert not gw.running
|
||||
|
||||
|
||||
def test_persistent_token_is_created_private_and_reused(tmp_path):
|
||||
import os
|
||||
import stat
|
||||
|
||||
from eco.web.gateway import persistent_token
|
||||
|
||||
path = tmp_path / "sub" / "web_token"
|
||||
first = persistent_token(str(path))
|
||||
assert len(first) >= 20 and persistent_token(str(path)) == first
|
||||
assert stat.S_IMODE(os.stat(path).st_mode) == 0o600
|
||||
path.unlink()
|
||||
assert persistent_token(str(path)) != first # deleting the file invalidates old clients
|
||||
@@ -0,0 +1,120 @@
|
||||
"""eco.web.viewmodels / backends: what the web client is told -- all of it
|
||||
plain JSON, built from real Assemblies (the demo namespace)."""
|
||||
import enum
|
||||
import json
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from eco.web import viewmodels
|
||||
from eco.web.backends import NotFound, SessionBackend
|
||||
from eco.web.demo import DemoNamespace
|
||||
|
||||
|
||||
class Color(enum.Enum):
|
||||
red = 0
|
||||
green = 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"value, expected",
|
||||
[
|
||||
(1.5, {"text": "1.5", "num": 1.5}),
|
||||
(3, {"text": "3", "num": 3}),
|
||||
(np.float64(2.0), {"text": "2.0", "num": 2.0}),
|
||||
(np.int32(7), {"text": "7", "num": 7}),
|
||||
(float("nan"), {"text": "nan"}),
|
||||
(True, {"text": "True", "bool": True}),
|
||||
(np.bool_(False), {"text": "False", "bool": False}),
|
||||
("open", {"text": "open", "cls": "green"}),
|
||||
("Closed ", {"text": "Closed ", "cls": "red"}),
|
||||
(Color.green, {"text": "green", "enum": ["red", "green"]}),
|
||||
],
|
||||
)
|
||||
def test_encode_value(value, expected):
|
||||
encoded = viewmodels.encode_value(value)
|
||||
assert encoded == expected
|
||||
json.dumps(encoded)
|
||||
|
||||
|
||||
def test_encode_value_clips_long_text():
|
||||
encoded = viewmodels.encode_value(np.arange(1000))
|
||||
assert len(encoded["text"]) == viewmodels.MAX_TEXT
|
||||
json.dumps(encoded)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"sent, last, expected",
|
||||
[("2.5", 1.0, 2.5), (3, 1.0, 3.0), ("4", 1, 4), ("on", False, True), ("green", Color.red, "green"), ("x", "y", "x")],
|
||||
)
|
||||
def test_coerce_target_follows_the_last_readback(sent, last, expected):
|
||||
result = viewmodels.coerce_target(sent, last)
|
||||
assert result == expected and type(result) is type(expected)
|
||||
|
||||
|
||||
def test_coerce_target_rejects_a_fraction_for_an_int():
|
||||
with pytest.raises(ValueError):
|
||||
viewmodels.coerce_target("2.5", 1)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def backend():
|
||||
return SessionBackend(DemoNamespace())
|
||||
|
||||
|
||||
def test_names_report_states_and_failure_reasons(backend):
|
||||
names = backend.names()
|
||||
assert {"mono", "lxt"} <= set(names["initialized"])
|
||||
assert "vacuum" in names["lazy"] or "vacuum" in names["initialized"]
|
||||
assert "IOC not reachable" in names["failed"]["broken"]
|
||||
json.dumps(names)
|
||||
|
||||
|
||||
def test_describe_an_assembly(backend):
|
||||
view, objects = viewmodels.describe(backend.resolve("mono"), "mono")
|
||||
json.dumps(view)
|
||||
kinds = {row["label"]: row["kind"] for row in view["rows"]}
|
||||
assert kinds == {"energy": "adjustable", "bragg": "adjustable", "pitch_rbv": "detector",
|
||||
"harmonic": "adjustable", "home_all": "trigger"}
|
||||
energy = next(r for r in view["rows"] if r["label"] == "energy")
|
||||
assert energy["name"] == "mono.energy" and energy["unit"] == "keV"
|
||||
assert objects["mono.energy"].get_current_value() == 7.0
|
||||
assert not view["svg"]
|
||||
|
||||
|
||||
def test_describe_lists_non_display_items_as_hidden(backend):
|
||||
view, _ = viewmodels.describe(backend.resolve("slits"), "slits")
|
||||
hidden = [r["label"] for r in view["rows"] if r.get("hidden")]
|
||||
assert hidden == ["blade_offset"]
|
||||
|
||||
|
||||
def test_describe_a_single_item(backend):
|
||||
view, objects = viewmodels.describe(backend.resolve("lxt"), "lxt")
|
||||
assert view["kind"] == "adjustable" and [r["name"] for r in view["rows"]] == ["lxt"]
|
||||
assert "lxt" in objects
|
||||
|
||||
|
||||
def test_resolve_initializes_a_lazy_component(backend):
|
||||
backend.resolve("vacuum")
|
||||
assert "vacuum" in backend.names()["initialized"]
|
||||
|
||||
|
||||
def test_resolve_dotted_names_and_refuses_private_ones(backend):
|
||||
assert backend.resolve("mono.energy").get_current_value() == 7.0
|
||||
with pytest.raises(NotFound):
|
||||
backend.resolve("mono._append")
|
||||
with pytest.raises(NotFound):
|
||||
backend.resolve("mono.nothing")
|
||||
with pytest.raises(NotFound):
|
||||
backend.resolve("nothing")
|
||||
with pytest.raises(NotFound):
|
||||
backend.resolve("broken")
|
||||
|
||||
|
||||
def test_svg_panel(backend):
|
||||
vacuum = backend.resolve("vacuum")
|
||||
assert viewmodels.has_svg_panel(vacuum)
|
||||
assert not viewmodels.has_svg_panel(backend.resolve("mono"))
|
||||
text, prefix = backend.svg(vacuum)
|
||||
assert text.startswith("<svg") and 'onclick="// eco: valve1"' in text
|
||||
assert prefix == "vacuum"
|
||||
@@ -0,0 +1,171 @@
|
||||
# Architecture
|
||||
|
||||
## 1. The one structural decision
|
||||
|
||||
A PWA is a thin client; it can't hold an eco namespace or Channel Access
|
||||
connections. So a PWA front-end is really two things:
|
||||
|
||||
- a **gateway**: a Python process that holds eco objects and serves a small JSON
|
||||
protocol over HTTP + websocket;
|
||||
- a **static client** (HTML/JS/CSS + manifest + service worker) that only talks
|
||||
that protocol.
|
||||
|
||||
This is the opposite of Voila, where every viewer gets its own kernel that
|
||||
imports eco. Here there is one eco process and any number of browsers.
|
||||
|
||||
## 2. Where the gateway runs — two hosting modes, same code
|
||||
|
||||
| Mode | Host process | Sees | Writes | Typical use |
|
||||
|---|---|---|---|---|
|
||||
| **A. shared** | the status server (`eco/status_server`, already holds an initialized namespace, always on) | namespace, values, monitors, recordings | **none** (read-only by policy) | "what is the beamline doing" from anywhere |
|
||||
| **B. session** | a user's own eco session (`eco.start_web()`, like `start_webapp()` today) | the above **plus** task queues, running scan, `user_ns`, memories | yes, through the normal `set_target_value` → `Changer` path | operating the experiment from a tablet/phone |
|
||||
|
||||
The gateway code only depends on a small "backend" interface (resolve a name to
|
||||
an object, list names with lazy/initialized/failed state, access queues if any).
|
||||
The status server provides one implementation, a live session another. Starting
|
||||
with mode B is simpler (no shared-service deployment); mode A comes almost free
|
||||
afterwards.
|
||||
|
||||
Mode A must stay read-only: the status server is a shared service running under
|
||||
`gac-bernina` for the DAQ, and must not become an unaudited write path.
|
||||
|
||||
## 3. Keeping three UI families in step (the parallelization question)
|
||||
|
||||
eco already uses the right pattern in a few places, it just isn't a rule yet:
|
||||
|
||||
```
|
||||
eco objects (Assembly / Adjustable / Detector / TaskQueue / Memory ...)
|
||||
│
|
||||
toolkit-free logic ("view models") ← already exists for some widgets:
|
||||
│ live_values.py, component_selector.py,
|
||||
│ tweak_panel.py, Memory (elements/memory.py),
|
||||
│ task_queue.py, log_timeline_common.py
|
||||
├── Qt adapter (display_qt, tweak_panel_qt, component_selector_qt, ...)
|
||||
├── ipywidgets adapter (display_widget, tweak_panel_ipy, component_selector_widget, ...)
|
||||
└── web adapter (gateway: view model → JSON messages) → PWA client
|
||||
```
|
||||
|
||||
Rules to adopt (only for new or touched code, no big-bang refactor):
|
||||
|
||||
1. **Logic first.** A feature's state and actions live in a module with no GUI
|
||||
imports (like `live_values.py` / `tweak_panel.py` today). Each front-end is an
|
||||
adapter.
|
||||
2. **View-model state is plain data** (dicts/lists/str/float/bool, numpy only at
|
||||
the edge). If it is JSON-serializable, the web adapter is nearly mechanical.
|
||||
A cheap test enforces this per view model.
|
||||
3. **Actions are named methods with plain arguments** (`move(i, sign)`,
|
||||
`set_step(i, step)`, `go(i, value)` — exactly `TweakController`'s shape).
|
||||
The gateway exposes them as protocol `call`s by an explicit allow-list, never
|
||||
by arbitrary attribute access.
|
||||
4. **Parity is tracked, not assumed** — PARITY.md has a column per front-end. A
|
||||
feature may stay Qt-only on purpose; that must be a recorded decision.
|
||||
5. Qt and ipywidgets keep running in-process exactly as now. Nothing in this plan
|
||||
requires changing them; the logic extraction is opportunistic.
|
||||
|
||||
What is *already* toolkit-free and directly reusable by the gateway:
|
||||
|
||||
- `eco/widgets/live_values.py` — `LiveReader` (subscribe-or-poll, "a subscription is
|
||||
not trusted until an event arrives"), `start_write`, `stop_move`, step helpers.
|
||||
This is the property grid's whole engine; the gateway uses it unchanged and
|
||||
pushes results down the websocket instead of into a Qt queue.
|
||||
- `eco/widgets/tweak_panel.py` — `TweakController` incl. `handle_key`.
|
||||
- `eco/widgets/component_selector.py` — tree/filter logic for pickers.
|
||||
- `eco/elements/memory.py` — Memory recall/save (memory_widget only renders it).
|
||||
- `eco/utilities/task_queue.py` — queues, tasks, output listeners.
|
||||
- `eco/widgets/log_timeline_common.py` — `TimelineEntry`.
|
||||
- SVG panels — `_widget_svg_panel()` already returns an SVG file; browsers render
|
||||
SVG natively, so this is the cheapest high-value port of all.
|
||||
|
||||
## 4. Client technology
|
||||
|
||||
Constraint: maintained by Python people, deployed on beamline hosts without a JS
|
||||
build pipeline.
|
||||
|
||||
Recommendation: **no build step to start with.** Plain ES modules + a small
|
||||
vendored view library (Preact + htm, or Lit; one file each, checked in), uPlot for
|
||||
strip charts, `<canvas>` for camera images, native SVG for panels. Add Vite/TypeScript
|
||||
only if the client grows past the point where that hurts (say, >5k lines).
|
||||
|
||||
- Manifest + service worker: cache the app shell only. **Never cache values**;
|
||||
stale beamline values shown as current would be actively dangerous. Offline
|
||||
view = "disconnected" banner, nothing else.
|
||||
- Every value carries its age; the client greys a value whose last update is
|
||||
older than its expected refresh.
|
||||
|
||||
## 5. Server technology
|
||||
|
||||
Prefer what the beamline environment already ships:
|
||||
|
||||
- **tornado** — certainly present (jupyter_server/voila depend on it), native
|
||||
websockets, its own event loop thread. First choice for mode B.
|
||||
- The status server is Flask (sync, no websockets). For mode A either add
|
||||
`flask-sock` (if available in bpy312) or run the tornado gateway as a second
|
||||
listener inside the same process. Decide at the time; check availability first
|
||||
(SPIKE.md prerequisites).
|
||||
|
||||
Threading: the gateway runs its own event loop on a background thread. It must
|
||||
**never** touch hardware on that loop — reads go through `LiveReader`'s pool,
|
||||
writes through `start_write` threads, exactly as the Qt grid does. Results are
|
||||
handed to the loop with `loop.add_callback`. It must not require the main thread,
|
||||
so `eco.utilities.mainthread` is irrelevant to it (an advantage over Qt).
|
||||
|
||||
Interaction with existing session machinery:
|
||||
|
||||
- writes go through `set_target_value` → `Changer`, so the access gate
|
||||
(`eco/elements/access.py`) and task-queue claims (`MoveBlocked`) apply unchanged.
|
||||
The gateway thread is "another thread", so a move on an adjustable claimed by a
|
||||
running queue task is blocked — which is the correct behaviour for a phone.
|
||||
- questions from `user_input` (`input()` from a queue task) are a later feature;
|
||||
initially they stay at the terminal.
|
||||
|
||||
## 6. Remote access (SSH only)
|
||||
|
||||
- The gateway binds **127.0.0.1 only**. Reaching it requires an SSH login to that
|
||||
host — SSH is the outer authentication.
|
||||
- On a shared console host any local account can reach 127.0.0.1, so the gateway
|
||||
**also** requires a per-session token (printed on start, carried in the URL
|
||||
once, then stored by the client). Mode B additionally restricts writes.
|
||||
- `http://localhost:<port>` counts as a *secure context* in browsers, so a PWA
|
||||
(service worker, install) works through a plain `ssh -L` without any TLS setup.
|
||||
|
||||
Per device:
|
||||
|
||||
| Device | How | Caveat |
|
||||
|---|---|---|
|
||||
| Laptop | `ssh -L 8097:localhost:8097 <host>` (+ jump host as usual) | none |
|
||||
| Android | Termux (`ssh -L ...`) or ConnectBot port forward, then browser at `localhost:8097` | keep the SSH app's notification / battery exemption so it survives in background |
|
||||
| iPhone/iPad | Blink Shell or Termius port forward | iOS suspends background apps; the tunnel dies minutes after switching away. Usable for "look now", not for "leave it open". |
|
||||
|
||||
Origin = `http://localhost:<port>`, so **always use the same local port**
|
||||
everywhere: browser storage, the installed PWA and its token are per origin.
|
||||
|
||||
Push notifications (Web Push) need the *sender* to reach Google/Apple/Mozilla
|
||||
push services outbound; whether a beamline host can (via proxy) is unknown, and a
|
||||
localhost origin may not get push on every browser. Treat notifications as out of
|
||||
scope for the SSH setup; revisit only if a PSI-hosted endpoint ever exists.
|
||||
|
||||
## 7. Safety model for writes (mode B)
|
||||
|
||||
- Off by default: `eco.start_web(writes=False)`.
|
||||
- With writes on: per-adjustable allow-list (default: whatever the access layer
|
||||
permits **and** is in an explicit `web_writable` set), confirmation sheet for
|
||||
absolute moves on touch devices, Stop always available and never confirmed.
|
||||
- Every web write is logged with client id (same audit file as `access.py`).
|
||||
- No arbitrary code execution from the client, ever — notably SVG panel
|
||||
`onclick="// eco: <command>"` commands are **not** executed by the gateway; in
|
||||
the web client a click on an SVG element opens that device's view instead.
|
||||
|
||||
## 8. Code layout (implemented, see README.md for the map)
|
||||
|
||||
```
|
||||
eco/web/ # Python, inside the package
|
||||
__init__.py # start_web(...) — lazily imported from eco/__init__.py
|
||||
gateway.py # tornado app, auth, websocket sessions
|
||||
backends.py # SessionBackend (mode B), StatusServerBackend (mode A)
|
||||
viewmodels/ # thin adapters over existing toolkit-free logic
|
||||
static/ # the PWA (or keep in web_frontend/client/ and ship as package data)
|
||||
tests/test_web_*.py # protocol + view-model JSON tests, no browser needed
|
||||
```
|
||||
|
||||
`eco_cli.py` gets a `--ui web` only once the spike succeeded. Packaging: a new
|
||||
optional extra `eco[web]` (tornado is already pulled by `lab`/`voila`).
|
||||
@@ -0,0 +1,67 @@
|
||||
# Qt → PWA feature parity
|
||||
|
||||
Inventory of `eco/widgets/` Qt functionality (state of 2026-10-25) and what each
|
||||
takes in the PWA. Effort is a rough guess for one developer who knows eco, given
|
||||
the gateway (SPIKE + phase 1) already exists — **d = days, w = weeks.**
|
||||
|
||||
Columns: **Qt** / **ipy** = exists for Qt / ipywidgets today. **Logic reusable** =
|
||||
a toolkit-free module the gateway can drive as-is. **Mobile value** = how much it
|
||||
matters on a phone/tablet.
|
||||
|
||||
## Tier 1 — core, port first
|
||||
|
||||
| Feature | Qt module(s) | ipy | Logic reusable | PWA work | Effort | Mobile value |
|
||||
|---|---|---|---|---|---|---|
|
||||
| Namespace browser (lazy/initialized/failed, tap to initialize, search) | `desktop_app._NamespaceLauncher`, `namespace_selector` | `widget_tray.NamespaceLauncherWidget` | Namespace API (`all_names`, `lazy_names`, `initialized_names`, `failed_names`, `__resolved__`) | list + filter view; init request runs on gateway pool with progress | 3–4 d | high |
|
||||
| Assembly property grid (rows, groups/colours, ▲/▼ tweak, entry, status dot, Stop) | `display_qt` | `display_widget` | **`live_values`** (all of it), `utilities.tables.section_row_styles` | grid component; touch-sized ▲/▼; numeric entry sheet; per-row state dot | 1–1.5 w | high |
|
||||
| Sub-assembly drill-down (`is_display='recursive'`) | `display_qt` | `display_widget` | Assembly tree | navigation stack (back button), breadcrumbs | 2 d | high |
|
||||
| SVG panels (beamline synoptic, prepump, alarm panel) | `svg_interactor` (Dash/WebKit), `_widget_svg_panel()` | same | `_widget_svg_panel()` returns the SVG | serve SVG inline, live colouring by id, pinch-zoom, tap → device view (no command exec) | 3–5 d | **very high** — cheapest win, already web-native |
|
||||
| Live-update transport, staleness, reconnect | — | — | `LiveReader` | websocket client, value ages, reconnect + resubscribe | (in spike) | essential |
|
||||
|
||||
## Tier 2 — operating an experiment
|
||||
|
||||
| Feature | Qt module(s) | ipy | Logic reusable | PWA work | Effort | Mobile value |
|
||||
|---|---|---|---|---|---|---|
|
||||
| Task queue view (tasks, state, pause/resume/abort, output follow) | `scan_launcher_qt.ScanQueuePanel`, `queue_output_qt` | partly (`%queue` only) | `task_queue` (listeners, `Task.output`) | list + live log; abort/pause behind confirm | 4–5 d | **very high** ("is my scan still running?") |
|
||||
| Running scan progress (step n/N, current positions, ETA) | partly in launcher | `scan_widget` | `scans.acquiring_scan`, `StepScan` | progress card | 2–3 d | very high |
|
||||
| Scan launcher (method forms, pickers, append to queue with test-run) | `scan_launcher_qt` (1.4k lines) | `scan_widget`, `scan_builder_widgets` | `task_queue` test-run, `Scans` signatures, `component_selector` | forms are much easier in HTML than Qt; picker is the work | 1.5–2 w | medium (tablet yes, phone rarely) |
|
||||
| Component / command picker | `component_selector_qt` | `component_selector_widget`, `component_picker_widget` | **`component_selector`** | tree/search list | 3 d | needed by launcher |
|
||||
| Tweak panel (1–4 axes, steps, keys) | `tweak_panel_qt` | `tweak_panel_ipy` | **`tweak_panel.TweakController`** | big touch buttons; keys still work on a laptop | 3–4 d | high (alignment from a tablet at the sample) |
|
||||
| Memory browser (filter, unfold, recall, save) | `memory_widget` (1.9k, Qt+Tk) | yes | **`elements/memory.py`** | list + diff view; recall behind confirm | 1 w | medium |
|
||||
| Indicator gadgets (LED, bar, strip chart, KPI tile, dial, slider) | `indicator_widgets`, `indicator_widgets_qt_simple` | `indicator_widgets_ipy` | value stream from `LiveReader` | HTML/SVG gadgets + uPlot strip chart — easier than Qt | 3–4 d | high |
|
||||
| User dashboard (arrange gadgets) | `dashboard_qt` (dock widgets) | — | — | CSS grid of cards, reorder; layout stored per client (localStorage) or per user on gateway | 3 d | high |
|
||||
| Alarms | `elements/alarm.py` panel | — | `AlarmSeverity` | alarm list + badge; in-app sound/vibration while open (no push, see ARCHITECTURE §6) | 2–3 d | very high |
|
||||
|
||||
## Tier 3 — heavy or specialised
|
||||
|
||||
| Feature | Qt module(s) | ipy | Logic reusable | PWA work | Effort | Mobile value |
|
||||
|---|---|---|---|---|---|---|
|
||||
| Camera viewer (cam_server stream, colormap, histogram, ROI/analysis, calibration) | `camserver_stream_qt` (2.8k), `camserver_panel_qt`, `camera_stream_qt` | `camera_stream_widget` | `FrameProcessor` / `ScreenpanelAnalysis` partly toolkit-free — check | gateway subscribes to bsread, downsamples, sends JPEG/WebP or 8-bit + colormap index to `<canvas>`; analysis numbers as data | basic view 1 w; full parity 3–4 w | medium — basic view yes, calibration/analysis stay Qt |
|
||||
| Stream plots / live plots (matplotlib windows) | stream plots, `CounterValue.plot_arrays` | inline mpl | the data, not the figures | send arrays, render with uPlot | 1 w | medium |
|
||||
| Log timeline | `log_timeline_qt` | `log_timeline_html` (already HTML!) | `log_timeline_common` | reuse the HTML renderer's approach | 2–3 d | low |
|
||||
| IOC finder (search, status, console output, restart) | `ioc_finder_qt` | `ioc_finder_widget` | `epics_utils.iocinfo` | search + status read-only easy; **restart stays desktop-only** | 2 d (read-only) | low–medium |
|
||||
| Status server monitor (health, reinit) | `status_server/gui.py` | — | `/health`, `/stats` | small status page | 1 d | medium |
|
||||
| Tips ("Did you know?") | `tip_qt` | — | `utilities/tips` | trivial | 0.5 d | low |
|
||||
|
||||
## Deliberately NOT ported
|
||||
|
||||
| Feature | Why |
|
||||
|---|---|
|
||||
| Embedded IPython console (`desktop_app`, `console_kernel`, `kernel_registry`) | Arbitrary code execution from a phone is the wrong risk/benefit; JupyterLab through the same SSH tunnel already provides a browser console for laptops. |
|
||||
| Executing SVG `onclick` / `<desc>` commands | Same reason; the web client maps a click to "open device view". |
|
||||
| Dock/tab/float window management | Replaced by a mobile navigation model (stack + dashboard grid), not emulated. |
|
||||
| Camera calibration dialog, IOC restart, other admin actions | Rare, consequential, desktop-only by policy. |
|
||||
| Qt heartbeat (`utilities/mainthread`) | Not needed — the gateway never uses the main thread. |
|
||||
| `containers.stack()` arbitrary composition | Possibly later as "saved layouts"; not a phase-1 concern. |
|
||||
|
||||
## Totals (rough)
|
||||
|
||||
- Spike: ~1 w.
|
||||
- Tier 1: ~3–4 w → a useful read-mostly mobile app.
|
||||
- Tier 2: ~6–8 w → you can operate an experiment from a tablet.
|
||||
- Tier 3 basic parts: ~3 w. Full camera parity is the one big item and may never
|
||||
be worth it.
|
||||
|
||||
Full Qt parity is not the goal; "everything you'd want away from the console" is
|
||||
roughly Tier 1 + Tier 2 + basic camera view, i.e. **~3 months of part-time work**,
|
||||
front-loadable so the first useful version arrives after ~1 month.
|
||||
@@ -0,0 +1,75 @@
|
||||
# Gateway ↔ client protocol (v0)
|
||||
|
||||
Implemented by `eco/web/client_session.py` (server) and `eco/web/static/app.js`
|
||||
(client). Rows marked *planned* are not implemented yet.
|
||||
|
||||
JSON over one websocket per client (`/ws?token=…`), plus a few plain HTTP GETs for
|
||||
static files and SVGs. Versioned from day one so client and gateway can be updated
|
||||
independently (a phone may keep a cached old client).
|
||||
|
||||
## Envelope
|
||||
|
||||
```json
|
||||
{"v": 0, "id": 17, "op": "subscribe", "args": {...}} // client → gateway
|
||||
{"v": 0, "re": 17, "ok": true, "data": {...}} // reply to id 17
|
||||
{"v": 0, "ev": "values", "data": {...}} // unsolicited event
|
||||
```
|
||||
|
||||
`id` is chosen by the client; every request gets exactly one reply (`ok:false`
|
||||
with `error: {type, message}` on failure — e.g. `MoveBlocked`, `AccessDenied`,
|
||||
`NotInitialized`, `WritesDisabled`).
|
||||
|
||||
## Item addressing
|
||||
|
||||
Items are addressed by **dotted eco name** (`alias.get_full_name()`, e.g.
|
||||
`"mono.energy"`). Every row a `describe` returned is remembered by the session
|
||||
under that name, and `subscribe`/`set`/... only accept such names. `describe`
|
||||
also accepts a top-level component or a public attribute path below one
|
||||
(`"vacuum.valve1"`, nothing starting with `_`), so deep links survive a reload.
|
||||
The client never sends expressions.
|
||||
|
||||
## Operations
|
||||
|
||||
| op | args | reply / effect |
|
||||
|---|---|---|
|
||||
| `hello` | `{client_version, client_id}` | `{protocol, label, mode: "session", writes: bool, flush_interval}` |
|
||||
| `ping` | `{}` | `{}` — the client sends it every 15 s; no reply in 8 s means the connection is dead |
|
||||
| `names` | `{}` | `{initialized:[…], lazy:[…], failed:{name: reason}}` |
|
||||
| `init` | `{name}` | *planned* — today `describe` of a lazy name initializes it |
|
||||
| `describe` | `{name}` | `{name, title, kind, svg, writable, doc?, rows:[{name, label, kind: "assembly"|"adjustable"|"detector"|"trigger"|"other", writable, unit?, enum?, group?, hidden?, svg?, button?}]}` — rows are the display collection, then the rest of the status collection as `hidden` (same split as `display_widget`/`display_qt`); initializes a lazy top-level name |
|
||||
| `subscribe` | `{names:[…]}` | added to this client's `LiveReader`; values arrive as `ev: "values"` |
|
||||
| `unsubscribe` | `{names:[…]}` | |
|
||||
| `set` | `{name, value}` | (mode B, writes on) `start_write`; state via `ev: "write"` (`moving`/`done`/`error`) |
|
||||
| `step` | `{name, sign, step}` | relative move (▲/▼) |
|
||||
| `stop` | `{name}` | `stop_move`; always allowed when writes are on |
|
||||
| `step_size` | `{name}` | `{step}` — the start value of the ▲/▼ step (the grids' `initial_step`) |
|
||||
| `trigger` | `{name}` | (writes on) runs an `AdjustableTrigger` |
|
||||
| — | — | SVG panels are plain HTTP: `GET /api/svg?name=…` returns the SVG, header `X-Eco-Prefix` is what click markers are relative to; the client re-fetches every 3 s |
|
||||
| `queues` *planned* | `{}` | queue list with tasks (mode B) |
|
||||
| `queue_call` *planned* | `{queue, action: "pause"|"resume"|"abort_current"|…}` | allow-listed subset of `TaskQueue` methods |
|
||||
| `queue_follow` *planned* | `{queue, from_task?}` | backlog + live `ev: "queue_output"` |
|
||||
| `tweak` *planned* | `{session_id, action, args}` | `TweakController` methods by allow-list |
|
||||
|
||||
## Events
|
||||
|
||||
```json
|
||||
{"ev": "values", "now": 1761390000.2, "data": {"mono.energy": {"text": "7.1", "num": 7.1, "t": 1761390000.12, "state": "live"|"subscribed"|"polled"}}}
|
||||
{"ev": "values", "now": ..., "data": {"mono.gauge": {"error": "no value (not connected?)", "state": "error", "t": ...}}}
|
||||
{"ev": "write", "data": {"name": "...", "state": "busy"|"moving"|"idle"|"error", "message": "..."}}
|
||||
{"ev": "queue_output", ...} // planned
|
||||
```
|
||||
|
||||
Value fields: `text` always; `num` for a finite real, `bool`, `enum` (labels), `cls`
|
||||
`"green"`/`"red"` for open/closed. Values are coalesced per item and flushed at most every 100 ms per client (latest
|
||||
value wins), so a 100 Hz channel cannot flood a phone over a tunnel. `t` is the
|
||||
read time on the gateway; the client shows age from it (clock skew: the gateway
|
||||
sends its own `now` in every `values` batch).
|
||||
|
||||
Value encoding: numbers/str/bool as JSON; numpy scalars converted; arrays only
|
||||
on explicit array subscriptions (later, binary frames); anything else
|
||||
`format_value()` from `live_values` as a string.
|
||||
|
||||
## Not in v0
|
||||
|
||||
Binary frames (camera images, arrays), user input routing, multi-user presence,
|
||||
saved layouts on the server.
|
||||
@@ -0,0 +1,95 @@
|
||||
# eco web front-end (PWA)
|
||||
|
||||
A fourth eco front-end, a **Progressive Web App** (an installable web page,
|
||||
touch-first, works on a phone), next to and independent of the other three:
|
||||
|
||||
| Front-end | Process model | Strength |
|
||||
|---|---|---|
|
||||
| `shell` (IPython) | the session | everything, for experts |
|
||||
| `desktop` (Qt) | in-process with the session | full-featured workbench on a console |
|
||||
| `lab` / `voila` (ipywidgets) | one kernel per viewer | notebooks, interactive exploration |
|
||||
| **`web` (PWA)** | one gateway process, many thin clients | phones/tablets/laptops, remote via SSH tunnel |
|
||||
|
||||
## Status (2026-10-30): spike implemented, not wired into eco
|
||||
|
||||
The code is in `eco/web/` and `tests/test_web_*.py`. **Nothing else in eco
|
||||
imports it** — not `eco/__init__.py`, not `eco_cli.py`, not `pyproject.toml` —
|
||||
so it can't affect other work and can be developed alongside it. It's
|
||||
switched on only by explicitly calling it (below). Wiring it in (an
|
||||
`eco.start_web()` wrapper, `--ui web`, an `eco[web]` extra, package-data for
|
||||
`eco/web/static/`) is a separate small step once the test on the beamline
|
||||
went well — see [SPIKE.md](SPIKE.md).
|
||||
|
||||
What works (tested against the simulated namespace, and in headless Chrome at
|
||||
phone size):
|
||||
|
||||
- namespace list (initialized / lazy / failed with reason), filter, tap a lazy
|
||||
component to initialize it
|
||||
- device view: an assembly's display rows (hidden ones behind a toggle), live
|
||||
values via `eco.widgets.live_values.LiveReader` (monitored where possible,
|
||||
polled otherwise — the same engine as the Qt and ipywidgets grids),
|
||||
status dot, value age and staleness, units, open/closed colouring
|
||||
- writes, **only when the gateway was started with them**: ▲/▼ with step,
|
||||
absolute move (dialog), enum select, Stop, triggers (confirmed) — through
|
||||
`set_target_value`, so the access gate and queue claims apply
|
||||
- SVG panels (`_widget_svg_panel` / `_show_svg`), live-refreshed, sanitized; a
|
||||
tap on a device opens its view (the `// eco: <cmd>` commands are **not run**)
|
||||
- token auth + HttpOnly cookie, binds 127.0.0.1, ping/reconnect after network
|
||||
drops, clean shutdown, service worker (app shell only), light/dark
|
||||
|
||||
Not yet: queues/scan progress, cameras, plots, alarms, dashboards, status-server
|
||||
(shared, read-only) mode, the monospace-label convention of the static beamline
|
||||
SVG. See [PARITY.md](PARITY.md) for the order.
|
||||
|
||||
## Try it
|
||||
|
||||
Anywhere, without a beamline (simulated motors, valves, an SVG panel, a slow and
|
||||
a broken component):
|
||||
|
||||
```bash
|
||||
python -m eco.web --demo # read-only
|
||||
python -m eco.web --demo --writes # with writes
|
||||
```
|
||||
|
||||
In a running eco session (uses the session's `namespace`):
|
||||
|
||||
```python
|
||||
from eco.web import start_web, stop_web
|
||||
gw = start_web() # read-only; prints the URL with the token
|
||||
gw = start_web(writes=True) # writes from the browser allowed
|
||||
stop_web()
|
||||
```
|
||||
|
||||
Open the printed `http://localhost:8097/?token=…`. From another machine, forward
|
||||
the port first: `ssh -L 8097:localhost:8097 <host>` (plus your usual jump host).
|
||||
Always use the same local port: browser storage and the installed app are per
|
||||
`localhost:<port>`.
|
||||
|
||||
Tests (per file, like the rest of the suite):
|
||||
|
||||
```bash
|
||||
PYTHONPATH=$PWD python -m pytest tests/test_web_viewmodels.py -q
|
||||
PYTHONPATH=$PWD python -m pytest tests/test_web_client_session.py -q
|
||||
PYTHONPATH=$PWD python -m pytest tests/test_web_gateway.py -q # needs tornado
|
||||
```
|
||||
|
||||
## Documents
|
||||
|
||||
1. [ARCHITECTURE.md](ARCHITECTURE.md) — gateway, hosting modes, how the UI families
|
||||
stay in step, security, SSH.
|
||||
2. [PARITY.md](PARITY.md) — every Qt feature, its PWA cost, what stays Qt-only.
|
||||
3. [PROTOCOL.md](PROTOCOL.md) — the wire protocol (v0, implemented).
|
||||
4. [SPIKE.md](SPIKE.md) — the beamline test: prerequisites, procedure, go/no-go.
|
||||
|
||||
## Code map
|
||||
|
||||
```
|
||||
eco/web/__init__.py start_web() / stop_web() / connection_help()
|
||||
eco/web/__main__.py python -m eco.web --demo
|
||||
eco/web/gateway.py tornado app on its own thread: token, static, /api/svg, /ws
|
||||
eco/web/client_session.py one client: the protocol, LiveReader, writes (no transport)
|
||||
eco/web/viewmodels.py eco objects/values -> plain JSON (no tornado)
|
||||
eco/web/backends.py SessionBackend (a live namespace); status-server backend later
|
||||
eco/web/demo.py simulated namespace
|
||||
eco/web/static/ index.html, app.js, style.css, sw.js, manifest, icon (no build step)
|
||||
```
|
||||
@@ -0,0 +1,80 @@
|
||||
# Spike: the first test
|
||||
|
||||
**Status 2026-10-30:** step 1 of the procedure (implementation) is done, see
|
||||
`eco/web/` and README.md; the scope below is covered, including the stretch
|
||||
(writes, behind `writes=True`). Next: the prerequisites, then steps 2-5 on a
|
||||
beamline console.
|
||||
|
||||
Purpose: answer "is this worth building?" with the smallest thing that exercises
|
||||
every risky part — gateway threading, live values over a websocket, SSH tunnel to
|
||||
a phone, PWA install, touch UX — without touching existing eco behaviour.
|
||||
|
||||
## Scope (in)
|
||||
|
||||
- `eco.start_web(port=8097, writes=False)` in a live session (mode B), lazily
|
||||
imported, nothing else changed.
|
||||
- Namespace list (initialized / lazy / failed), tap to initialize.
|
||||
- One assembly view: property grid rows with live values and value age, via
|
||||
`live_values.LiveReader`.
|
||||
- One SVG panel (beamline synoptic or prepump) with live colouring.
|
||||
- Manifest + service worker (app shell only), install on phone.
|
||||
- Token auth, bind to 127.0.0.1.
|
||||
|
||||
## Scope (out)
|
||||
|
||||
Writes, queues, scans, cameras, plots, notifications, status-server mode A.
|
||||
(Optional stretch, only if time: writes for **one** harmless adjustable,
|
||||
e.g. a soft/memory adjustable, to test the confirm/Stop UX.)
|
||||
|
||||
## Prerequisites — check before starting (each ~minutes)
|
||||
|
||||
- [ ] `tornado` importable in bpy312 (expected yes; via jupyter_server) — the gateway's only extra dependency. Also note
|
||||
whether `flask_sock`/`starlette`/`uvicorn` are there (for mode A later).
|
||||
`/sf/bernina/applications/python/.pixi/envs/bpy312/bin/python -c "import tornado; print(tornado.version)"`
|
||||
- [ ] SSH port forwarding allowed on the target console host
|
||||
(`sshd -T | grep -i allowtcpforwarding` or simply try `ssh -L 8097:localhost:8097 <host>`
|
||||
from a laptop, through the usual jump host).
|
||||
- [ ] The same from a phone: Android Termux/ConnectBot, iOS Blink/Termius — with
|
||||
the PSI auth method in use (key + jump host / MFA). **This is the most likely
|
||||
blocker**; check it first.
|
||||
- [ ] Port 8097 unused on the host (status server uses 8091, docs site 8095).
|
||||
- [ ] Ask (informally) whether IT has a stance on long-lived SSH forwards from
|
||||
mobile devices. SSH itself is sanctioned; this is about expectations, not
|
||||
permission for a new service.
|
||||
|
||||
## Procedure
|
||||
|
||||
1. ~~Implement (`eco/web/` + static client)~~ — done; try it first with `python -m eco.web --demo`.
|
||||
2. Laptop: tunnel, open `http://localhost:8097/?token=…`, browse, open assembly,
|
||||
open SVG. Measure: time to first value, update latency vs. Qt grid side by side.
|
||||
3. Phone (Android first, then iOS): same via tunnel app; install PWA
|
||||
("Add to Home screen"); use it for a day of a real shift in read-only mode.
|
||||
4. Kill the tunnel / lock the phone / switch networks — client must show
|
||||
"disconnected", then recover and resubscribe without reload.
|
||||
5. Load: 5 clients × 200 subscribed items; check session responsiveness
|
||||
(prompt latency, scan step time) is unchanged — the gateway must not compete
|
||||
with the session for the CA lock in a noticeable way (pyepics serialises CA
|
||||
calls behind one global lock; see `eco/epics_utils/ca_tuning.py` and
|
||||
`eco/status_server/DESIGN.md` §15 for the measured `get_status()` timings).
|
||||
|
||||
## Go / no-go
|
||||
|
||||
Go if all of:
|
||||
|
||||
- Values on the phone within 2 s of opening a view, updates < 0.5 s behind Qt.
|
||||
- Reconnect works without user action after a network switch.
|
||||
- No measurable effect on scan-step duration with 5 clients connected.
|
||||
- At least one person who was on shift says they'd use it.
|
||||
|
||||
No-go / rethink if the phone tunnel is impractical (auth, iOS backgrounding) —
|
||||
then the PWA is a laptop/tablet tool only, which changes priorities (Tier 2 scan
|
||||
launcher before mobile polish), or the question of a PSI-hosted endpoint has to
|
||||
be raised properly.
|
||||
|
||||
## Wiring it in, once the test went well (small, touches shared files)
|
||||
|
||||
- `eco/__init__.py`: a lazy `start_web()` wrapper like `start_webapp()`.
|
||||
- `eco_cli.py`: `--ui web` (start a session, then `start_web()`).
|
||||
- `pyproject.toml`: `eco[web] = ["tornado"]`; `eco/web/static/*` under
|
||||
`[tool.setuptools.package-data]` (needed for `pip install`, not for checkouts).
|
||||
- `docs/`: a short page on starting it, and the gateway's threading and security rules.
|
||||
Reference in new issue
Block a user