diff --git a/README.md b/README.md
index 7c9b111..3beebb1 100644
--- a/README.md
+++ b/README.md
@@ -117,12 +117,40 @@ group, `l2power`, one peer per PDU. `daemons/l2power/` holds a shared base
and one script per PDU family:
```bash
-uv run daemons/l2power/eaton_pdu -c config/l2power/l2power_pdu1.yaml
-libby modify l2power.pdu1.state3 false
+uv run daemons/l2power/eaton_pdu -c config/l2power/l2power_pdu_137.yaml
+libby modify l2power.pdu-137.state3 false
```
+A daemon on another host reaches the instrument broker through
+`LRIS2_BROKER_HOST` in `/etc/lris2/secrets.env`; a `rabbitmq_url` in the daemon
+config takes precedence. The broker admits remote guests with
+`loopback_users = none` in `/etc/rabbitmq/rabbitmq.conf`. Every variable that
+goes in `secrets.env` is listed in [`systemd/README.md`](systemd/README.md#secrets).
+
For running daemons as services, see [`systemd/README.md`](systemd/README.md).
+## The CSU
+
+`daemons/csu` serves the configurable slit unit as `lris2.csu`: each bar's
+position, velocity, enable, halt and fault, plus drive telemetry (board
+temperature, I2t, current, supply). It drives the PLC motion server over ADS
+through coo-ethercat; `plc/` holds that PLC program and `plc/setup-csu.ps1`
+installs it into a TwinCAT project.
+
+```bash
+uv run daemons/csu -c config/csu/csu.yaml
+libby modify lris2.csu.positionvalue6 -260.0
+```
+
+`lris2-csu-demo` is a browser demo with the webcam stream and bar controls,
+laid out as in `config/csu/layout.yaml`, per-bar charts of drive temperature
+and current, and the CSU lab PDU's outlets with a switch for the drives. It
+drives the bars only through `lris2.csu` and the PDU through `l2power.pdu-ethercat`,
+so it runs anywhere the broker is reachable. On the CSU host,
+`install.sh --extra csu-demo` installs `lris2-csu-demo.service`, which serves it
+on port 8088; taking control needs `LRIS2_CSU_DEMO_PASSWORD` from
+`/etc/lris2/secrets.env`.
+
## Testing
Tests mirror the `src/` layout under `tests/`.
diff --git a/config/common/keygrabber.yaml b/config/common/keygrabber.yaml
index 485f838..03e8991 100644
--- a/config/common/keygrabber.yaml
+++ b/config/common/keygrabber.yaml
@@ -45,8 +45,19 @@ collections:
timeout_s: 5.0
# One telnet query per keyword, so a batch of 32 takes a couple of seconds
- pdu1:
- peer: l2power.pdu1
+ pdu-137:
+ peer: l2power.pdu-137
+ keywords: ["state%", "current%", "power%", "energy%"]
+ timeout_s: 10.0
+ # Drive telemetry and motion state; positions are commanded, so they stay out
+ csu:
+ peer: lris2.csu
+ keywords: ["boardtemp%", "i2tmotor%", "i2tstage%", "current%", "supply%",
+ "ismoving%", "isenabled%", "error%", "plcstate", "isconnected"]
+ interval_s: 10.0
+ timeout_s: 5.0
+ pdu-ethercat:
+ peer: l2power.pdu-ethercat
keywords: ["state%", "current%", "power%", "energy%"]
timeout_s: 10.0
diff --git a/config/csu/csu.yaml b/config/csu/csu.yaml
new file mode 100644
index 0000000..9db7992
--- /dev/null
+++ b/config/csu/csu.yaml
@@ -0,0 +1,53 @@
+#
+# Usage:
+# daemons/csu -c config/csu/csu.yaml
+#
+# The CSU bars behind the CX-LAB01 PLC motion server. Bar CSU-N sits in PLC slot
+# N+1, which is linked to NC axis N+1 and EPOS4 drive N+1 (station 1001+N).
+
+peer_id: csu
+group_id: lris2
+
+hardware:
+ sim: false # true serves simulated bars, no PLC
+
+topology:
+ name: csu
+ backend: twincat
+ transport:
+ host: 192.168.30.99
+ ams_net_id: 5.57.12.96.1.1
+ ams_port: 851
+ master_net_id: 5.57.12.96.4.1
+ # This host's AMS net id; the PLC needs a static route back to it
+ local_net_id: 192.168.30.1.1.1
+ defaults:
+ units: {name: mm}
+ limits: {velocity: 5.0}
+ axes:
+ - {name: CSU-0, plc_index: 1, station_address: 1001}
+ - {name: CSU-1, plc_index: 2, station_address: 1002}
+ - {name: CSU-2, plc_index: 3, station_address: 1003}
+ - {name: CSU-3, plc_index: 4, station_address: 1004}
+ - {name: CSU-4, plc_index: 5, station_address: 1005}
+ - {name: CSU-5, plc_index: 6, station_address: 1006}
+ - {name: CSU-6, plc_index: 7, station_address: 1007}
+ - {name: CSU-7, plc_index: 8, station_address: 1008}
+ - {name: CSU-8, plc_index: 9, station_address: 1009}
+ - {name: CSU-9, plc_index: 10, station_address: 1010}
+ - {name: CSU-10, plc_index: 11, station_address: 1011}
+ - {name: CSU-11, plc_index: 12, station_address: 1012}
+ - {name: CSU-12, plc_index: 13, station_address: 1013}
+ - {name: CSU-13, plc_index: 14, station_address: 1014}
+ - {name: CSU-14, plc_index: 15, station_address: 1015}
+ - {name: CSU-15, plc_index: 16, station_address: 1016}
+ - {name: CSU-16, plc_index: 17, station_address: 1017}
+ - {name: CSU-17, plc_index: 18, station_address: 1018}
+ - {name: CSU-18, plc_index: 19, station_address: 1019}
+ - {name: CSU-19, plc_index: 20, station_address: 1020}
+ - {name: CSU-20, plc_index: 21, station_address: 1021}
+ - {name: CSU-21, plc_index: 22, station_address: 1022}
+ - {name: CSU-22, plc_index: 23, station_address: 1023}
+
+logging:
+ level: INFO
diff --git a/config/csu/layout.yaml b/config/csu/layout.yaml
new file mode 100644
index 0000000..40f2385
--- /dev/null
+++ b/config/csu/layout.yaml
@@ -0,0 +1,21 @@
+# Physical slot of each CSU bar as seen from the webcam: side of the slit, row counted
+# from the top (1-12), and which way a positive move takes the bar on screen.
+# Bars not listed here are not in service.
+rows: 12
+bars:
+ CSU-0: {side: left, row: 7, plus: left}
+ CSU-1: {side: left, row: 8, plus: left}
+ CSU-2: {side: left, row: 9, plus: left}
+ CSU-3: {side: left, row: 10, plus: left}
+ CSU-4: {side: left, row: 11, plus: left}
+ CSU-5: {side: left, row: 12, plus: left}
+ CSU-6: {side: left, row: 5, plus: right}
+ CSU-7: {side: left, row: 4, plus: right}
+ CSU-8: {side: left, row: 3, plus: right}
+ CSU-9: {side: left, row: 2, plus: right}
+ CSU-10: {side: left, row: 1, plus: right}
+ CSU-13: {side: right, row: 9, plus: left}
+ CSU-14: {side: right, row: 10, plus: left}
+ CSU-15: {side: right, row: 11, plus: left}
+ CSU-16: {side: right, row: 12, plus: left}
+ CSU-18: {side: right, row: 5, plus: right}
diff --git a/config/l2power/l2power_pdu1.yaml b/config/l2power/l2power_pdu_137.yaml
similarity index 72%
rename from config/l2power/l2power_pdu1.yaml
rename to config/l2power/l2power_pdu_137.yaml
index 980a53d..c2e746a 100644
--- a/config/l2power/l2power_pdu1.yaml
+++ b/config/l2power/l2power_pdu_137.yaml
@@ -1,12 +1,12 @@
# l2power PDU 1 - Eaton EMAT-08 (epduB2)
#
# Usage:
-# daemons/l2power/eaton_pdu -c config/l2power/l2power_pdu1.yaml
+# daemons/l2power/eaton_pdu -c config/l2power/l2power_pdu_137.yaml
#
-# Addressed as l2power.pdu1, e.g.
-# libby show l2power.pdu1.state1
+# Addressed as l2power.pdu-137, e.g.
+# libby show l2power.pdu-137.state1
-peer_id: pdu1
+peer_id: pdu-137
group_id: l2power
hardware:
@@ -20,7 +20,7 @@ hardware:
# Telnet login from /etc/lris2/secrets.env. The password is the PDU's serial
# number, so each PDU has its own variable
username_env: LRIS2_PDU_USERNAME
- password_env: LRIS2_PDU1_PASSWORD
+ password_env: LRIS2_PDU137_PASSWORD
logging:
level: INFO
diff --git a/config/l2power/l2power_pdu_ethercat.yaml b/config/l2power/l2power_pdu_ethercat.yaml
new file mode 100644
index 0000000..95b6719
--- /dev/null
+++ b/config/l2power/l2power_pdu_ethercat.yaml
@@ -0,0 +1,28 @@
+# l2power pdu-ethercat - Eaton EMAT-08 (epduC5) in the CSU lab
+#
+# Usage:
+# daemons/l2power/eaton_pdu -c config/l2power/l2power_pdu_ethercat.yaml
+#
+# Addressed as l2power.pdu-ethercat, e.g.
+# libby show l2power.pdu-ethercat.power_ethercat
+
+peer_id: pdu-ethercat
+group_id: l2power
+
+hardware:
+ # Lease pinned by the dnsmasq dhcp-host entry for its MAC on lris2-ethercat
+ ip_address: 192.168.30.200
+ tcp_port: 23
+ outlet_count: 8
+ outlet_names:
+ 1: windows
+ 2: lantronix
+ 4: ethercat
+ 5: plc
+ 7: gateway
+ # Telnet login from /etc/lris2/secrets.env; the password is the PDU's serial number
+ username_env: LRIS2_PDU_USERNAME
+ password_env: LRIS2_PDUETHERCAT_PASSWORD
+
+logging:
+ level: INFO
diff --git a/daemons/csu b/daemons/csu
new file mode 100755
index 0000000..45b4c28
--- /dev/null
+++ b/daemons/csu
@@ -0,0 +1,131 @@
+#!/usr/bin/env python3
+'''LRIS2 CSU daemon: the slit bars as libby keywords, driven over ADS through the PLC'''
+import argparse
+import dataclasses
+import sys
+import threading
+
+import pyads
+from cooethercat import AxisError, AxisSet, ControllerState
+from cooethercat.backends.sim import open_simulated
+from cooethercat.backends.twincat import open_twincat
+from cooethercat.config import Backend, parse_topology
+
+from lris2.csu.keywords import CsuKeywords
+from lris2.daemon import Lris2Daemon
+
+TRANSPORT_ERRORS = (OSError, pyads.ADSError)
+# How often the watchdog checks the PLC link, and so how soon a dropped link heals
+WATCHDOG_S = 5.0
+
+
+class Csu(Lris2Daemon): # pylint: disable=W0223
+ '''Daemon for the LRIS2 configurable slit unit'''
+
+ group_id = "lris2"
+ topics = {}
+
+ def __init__(self):
+ super().__init__()
+ self.axes: AxisSet | None = None
+ self.keywords: CsuKeywords | None = None
+ self.topology = None
+ self.sim = False
+ self._stopping = threading.Event()
+
+ def on_start(self, libby=None): # pylint: disable=W0613
+ '''Register keywords, then connect; the daemon stays up if the PLC is unreachable'''
+ self.sim = bool(self.get_config("hardware.sim", False))
+ self.topology = parse_topology(self.get_config("topology"), source="topology")
+ if self.sim:
+ self.topology = dataclasses.replace(self.topology, backend=Backend.SIM)
+ self.axes = self._open_axes()
+ self.keywords = CsuKeywords(self.axes, TRANSPORT_ERRORS)
+ self.keywords.register(self.keyword_registry)
+ self.keyword_registry.bool("isconnected", getter=self.is_connected,
+ setter=self.set_connected,
+ description="PLC reachable; write true to reconnect")
+ self.keyword_registry.string("plcstate", getter=self.plc_state,
+ description="PLC runtime mode: run, stop, config or other")
+ self.keyword_registry.trigger("shutdown", action=self.shutdown,
+ description="Stop the daemon; refused while a bar moves")
+ self.logger.info("CSU daemon serving %d bars (%s)", len(self.axes),
+ "simulated" if self.sim else self.topology.transport.host)
+ threading.Thread(target=self._watch_link, name="plc link", daemon=True).start()
+
+ def on_stop(self, libby=None): # pylint: disable=W0613
+ '''Close the PLC connection; the PLC keeps each bar's enable state'''
+ self._stopping.set()
+ if self.axes is not None:
+ self.axes.backend.close()
+
+ def _open_axes(self) -> AxisSet:
+ if self.sim:
+ return open_simulated(self.topology)
+ return open_twincat(self.topology)
+
+ def is_connected(self) -> bool:
+ '''Return whether the PLC is in Run and a status read reaches it'''
+ try:
+ if self.axes.backend.controller_state() is not ControllerState.RUN:
+ return False
+ next(iter(self.axes)).status()
+ except (AxisError, *TRANSPORT_ERRORS):
+ return False
+ return True
+
+ def plc_state(self) -> str:
+ '''Return the PLC runtime mode, as read from the TwinCAT system service'''
+ try:
+ return str(self.axes.backend.controller_state())
+ except TRANSPORT_ERRORS as error:
+ raise RuntimeError(f"PLC unreachable: {error}") from error
+
+ def set_connected(self, value) -> None:
+ '''Reconnect on true; false is refused, since keywords need the connection'''
+ if not value:
+ raise RuntimeError("the CSU daemon always holds its PLC connection")
+ self.axes.backend.close()
+ self.axes.backend.open()
+
+ def _watch_link(self) -> None:
+ '''Reopen the PLC link whenever a status read fails, e.g. after a drive power cycle'''
+ failing = False
+ while not self._stopping.wait(WATCHDOG_S):
+ try:
+ next(iter(self.axes)).status()
+ except TRANSPORT_ERRORS as error:
+ if not failing:
+ self.logger.warning("PLC link lost (%s); reconnecting", error)
+ failing = True
+ self._reopen()
+ continue
+ if failing:
+ self.logger.info("PLC link restored")
+ failing = False
+
+ def _reopen(self) -> None:
+ try:
+ self.axes.backend.close()
+ self.axes.backend.open()
+ except TRANSPORT_ERRORS as error:
+ self.logger.debug("reconnect failed: %s", error)
+
+ def shutdown(self) -> None:
+ '''Stop the daemon unless a bar is moving'''
+ if self.keywords.any_moving():
+ raise RuntimeError("a bar is moving; halt first")
+ self.request_stop()
+
+
+def main():
+ '''Parse arguments and serve until stopped'''
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("-c", "--config", required=True, help="daemon config YAML")
+ parser.add_argument("-d", "--daemon-id", help="override peer_id")
+ args = parser.parse_args()
+ Csu.from_config_file(args.config, args.daemon_id).serve()
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/daemons/l2power/pdu_base.py b/daemons/l2power/pdu_base.py
index eb6ca48..540e167 100644
--- a/daemons/l2power/pdu_base.py
+++ b/daemons/l2power/pdu_base.py
@@ -136,7 +136,7 @@ def call(*value: Any) -> Any:
raise self._error(f"{label}: {e}") from e
return call
- def on_start(self, libby) -> None: # pylint: disable=W0613
+ def on_start(self, libby=None) -> None: # pylint: disable=W0613
"""Read config, register keywords, and connect to the PDU."""
self.host = self.get_config("hardware.ip_address")
self.port = int(self.get_config("hardware.tcp_port", self.default_port))
diff --git a/grafana/lris2-general-dashboard.json b/grafana/lris2-general-dashboard.json
new file mode 100644
index 0000000..ce5bcf1
--- /dev/null
+++ b/grafana/lris2-general-dashboard.json
@@ -0,0 +1,1233 @@
+{
+ "annotations": {
+ "list": [
+ {
+ "builtIn": 1,
+ "datasource": {
+ "type": "grafana",
+ "uid": "-- Grafana --"
+ },
+ "enable": true,
+ "hide": true,
+ "iconColor": "rgba(0, 211, 255, 1)",
+ "name": "Annotations & Alerts",
+ "type": "dashboard"
+ },
+ {
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "enable": true,
+ "iconColor": "rgba(80, 140, 255, 0.25)",
+ "name": "CSU motion",
+ "target": {
+ "query": "from(bucket: \"LRIS2\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r.peer == \"csu\" and r._measurement =~ /^ismoving[0-9]+$/ and r._value == true)\n |> group()\n |> aggregateWindow(every: 10s, fn: count, createEmpty: false)\n |> map(fn: (r) => ({_time: r._time, _value: r._value, text: \"moving\"}))",
+ "refId": "Anno"
+ }
+ }
+ ]
+ },
+ "editable": true,
+ "fiscalYearStartMonth": 0,
+ "graphTooltip": 1,
+ "links": [],
+ "liveNow": false,
+ "panels": [
+ {
+ "type": "row",
+ "title": "CSU (lris2.csu)",
+ "collapsed": false,
+ "panels": [],
+ "id": 1,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 0
+ },
+ "pluginVersion": "11.2.0"
+ },
+ {
+ "type": "stat",
+ "title": "PLC",
+ "description": "TwinCAT runtime mode; anything but Run means no bar can move",
+ "id": 2,
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "gridPos": {
+ "h": 4,
+ "w": 4,
+ "x": 0,
+ "y": 1
+ },
+ "targets": [
+ {
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "query": "import \"regexp\"\nimport \"strings\"\nfrom(bucket: \"LRIS2\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r.peer == \"csu\" and r._measurement =~ /^plcstate$/)\n |> last()\n |> keep(columns: [\"_time\", \"_value\"])",
+ "refId": "A"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "unit": "none",
+ "mappings": [
+ {
+ "type": "value",
+ "options": {
+ "run": {
+ "color": "green",
+ "text": "Run"
+ },
+ "config": {
+ "color": "red",
+ "text": "Config"
+ },
+ "stop": {
+ "color": "red",
+ "text": "Stop"
+ },
+ "other": {
+ "color": "orange",
+ "text": "Other"
+ }
+ }
+ }
+ ],
+ "color": {
+ "mode": "thresholds"
+ },
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ {
+ "color": "blue",
+ "value": null
+ }
+ ]
+ }
+ },
+ "overrides": []
+ },
+ "options": {
+ "colorMode": "background",
+ "graphMode": "none",
+ "textMode": "value",
+ "reduceOptions": {
+ "calcs": [
+ "lastNotNull"
+ ],
+ "fields": "/^_value$/",
+ "values": false
+ }
+ },
+ "pluginVersion": "11.2.0"
+ },
+ {
+ "type": "stat",
+ "title": "Bars enabled",
+ "description": "",
+ "id": 3,
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "gridPos": {
+ "h": 4,
+ "w": 4,
+ "x": 4,
+ "y": 1
+ },
+ "targets": [
+ {
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "query": "from(bucket: \"LRIS2\")\n |> range(start: -1h)\n |> filter(fn: (r) => r.peer == \"csu\" and r._measurement =~ /^isenabled[0-9]+$/)\n |> last()\n |> map(fn: (r) => ({r with _value: if r._value then 1 else 0}))\n |> group()\n |> sum()",
+ "refId": "A"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "unit": "none",
+ "mappings": [],
+ "color": {
+ "mode": "thresholds"
+ },
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ {
+ "color": "blue",
+ "value": null
+ }
+ ]
+ }
+ },
+ "overrides": []
+ },
+ "options": {
+ "colorMode": "background",
+ "graphMode": "none",
+ "textMode": "value",
+ "reduceOptions": {
+ "calcs": [
+ "lastNotNull"
+ ],
+ "fields": "",
+ "values": false
+ }
+ },
+ "pluginVersion": "11.2.0"
+ },
+ {
+ "type": "stat",
+ "title": "Bars faulted",
+ "description": "",
+ "id": 4,
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "gridPos": {
+ "h": 4,
+ "w": 4,
+ "x": 8,
+ "y": 1
+ },
+ "targets": [
+ {
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "query": "from(bucket: \"LRIS2\")\n |> range(start: -1h)\n |> filter(fn: (r) => r.peer == \"csu\" and r._measurement =~ /^error[0-9]+$/)\n |> last()\n |> map(fn: (r) => ({r with _value: if r._value != 0 then 1 else 0}))\n |> group()\n |> sum()",
+ "refId": "A"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "unit": "none",
+ "mappings": [],
+ "color": {
+ "mode": "thresholds"
+ },
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ {
+ "color": "green",
+ "value": null
+ },
+ {
+ "color": "red",
+ "value": 1
+ }
+ ]
+ }
+ },
+ "overrides": []
+ },
+ "options": {
+ "colorMode": "background",
+ "graphMode": "none",
+ "textMode": "value",
+ "reduceOptions": {
+ "calcs": [
+ "lastNotNull"
+ ],
+ "fields": "",
+ "values": false
+ }
+ },
+ "pluginVersion": "11.2.0"
+ },
+ {
+ "type": "stat",
+ "title": "Hottest drive",
+ "description": "",
+ "id": 5,
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "gridPos": {
+ "h": 4,
+ "w": 4,
+ "x": 12,
+ "y": 1
+ },
+ "targets": [
+ {
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "query": "from(bucket: \"LRIS2\")\n |> range(start: -1h)\n |> filter(fn: (r) => r.peer == \"csu\" and r._measurement =~ /^boardtemp[0-9]+$/)\n |> last()\n |> group()\n |> max()",
+ "refId": "A"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "unit": "celsius",
+ "mappings": [],
+ "color": {
+ "mode": "thresholds"
+ },
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ {
+ "color": "green",
+ "value": null
+ },
+ {
+ "color": "yellow",
+ "value": 75
+ },
+ {
+ "color": "red",
+ "value": 85
+ }
+ ]
+ }
+ },
+ "overrides": []
+ },
+ "options": {
+ "colorMode": "background",
+ "graphMode": "none",
+ "textMode": "value",
+ "reduceOptions": {
+ "calcs": [
+ "lastNotNull"
+ ],
+ "fields": "",
+ "values": false
+ }
+ },
+ "pluginVersion": "11.2.0"
+ },
+ {
+ "type": "stat",
+ "title": "Last CSU sample",
+ "description": "",
+ "id": 6,
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "gridPos": {
+ "h": 4,
+ "w": 4,
+ "x": 16,
+ "y": 1
+ },
+ "targets": [
+ {
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "query": "from(bucket: \"LRIS2\")\n |> range(start: -7d)\n |> filter(fn: (r) => r.peer == \"csu\" and r._measurement =~ /^supply[0-9]+$/)\n |> last()\n |> group()\n |> max(column: \"_time\")\n |> map(fn: (r) => ({_time: r._time, _value: float(v: int(v: now()) - int(v: r._time)) / 1000000000.0}))",
+ "refId": "A"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "unit": "s",
+ "mappings": [],
+ "color": {
+ "mode": "thresholds"
+ },
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ {
+ "color": "green",
+ "value": null
+ },
+ {
+ "color": "yellow",
+ "value": 60
+ },
+ {
+ "color": "red",
+ "value": 300
+ }
+ ]
+ }
+ },
+ "overrides": []
+ },
+ "options": {
+ "colorMode": "background",
+ "graphMode": "none",
+ "textMode": "value",
+ "reduceOptions": {
+ "calcs": [
+ "lastNotNull"
+ ],
+ "fields": "",
+ "values": false
+ }
+ },
+ "pluginVersion": "11.2.0"
+ },
+ {
+ "type": "stat",
+ "title": "Last PDU sample",
+ "description": "",
+ "id": 7,
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "gridPos": {
+ "h": 4,
+ "w": 4,
+ "x": 20,
+ "y": 1
+ },
+ "targets": [
+ {
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "query": "from(bucket: \"LRIS2\")\n |> range(start: -7d)\n |> filter(fn: (r) => r.peer =~ /^${pdu:regex}$/ and r._measurement =~ /^power(_[A-Za-z0-9_]+|[0-9]+)$/)\n |> last()\n |> group()\n |> max(column: \"_time\")\n |> map(fn: (r) => ({_time: r._time, _value: float(v: int(v: now()) - int(v: r._time)) / 1000000000.0}))",
+ "refId": "A"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "unit": "s",
+ "mappings": [],
+ "color": {
+ "mode": "thresholds"
+ },
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ {
+ "color": "green",
+ "value": null
+ },
+ {
+ "color": "yellow",
+ "value": 60
+ },
+ {
+ "color": "red",
+ "value": 300
+ }
+ ]
+ }
+ },
+ "overrides": []
+ },
+ "options": {
+ "colorMode": "background",
+ "graphMode": "none",
+ "textMode": "value",
+ "reduceOptions": {
+ "calcs": [
+ "lastNotNull"
+ ],
+ "fields": "",
+ "values": false
+ }
+ },
+ "pluginVersion": "11.2.0"
+ },
+ {
+ "type": "state-timeline",
+ "title": "Bars",
+ "description": "Per bar: green while enabled, blue while moving",
+ "id": 8,
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "gridPos": {
+ "h": 10,
+ "w": 24,
+ "x": 0,
+ "y": 5
+ },
+ "targets": [
+ {
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "query": "import \"regexp\"\nimport \"strings\"\nfrom(bucket: \"LRIS2\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r.peer == \"csu\" and r._measurement =~ /^(isenabled|ismoving)[0-9]+$/)\n |> map(fn: (r) => ({_time: r._time, _field: \"CSU-\" + (if strings.strlen(v: regexp.replaceAllString(r: /^[a-z0-9]*[a-z]/, v: r._measurement, t: \"\")) == 1 then \"0\" else \"\") + regexp.replaceAllString(r: /^[a-z0-9]*[a-z]/, v: r._measurement, t: \"\"),\n _value: if not r._value then 0 else if strings.hasPrefix(v: r._measurement, prefix: \"ismoving\") then 2 else 1}))\n |> group(columns: [\"_field\"])\n |> sort(columns: [\"_time\"])\n |> aggregateWindow(every: v.windowPeriod, fn: max, createEmpty: false)",
+ "refId": "A"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "displayName": "${__field.labels._field}",
+ "custom": {
+ "fillOpacity": 80,
+ "lineWidth": 0
+ },
+ "mappings": [
+ {
+ "type": "value",
+ "options": {
+ "0": {
+ "text": "off",
+ "color": "transparent"
+ },
+ "1": {
+ "text": "enabled",
+ "color": "green"
+ },
+ "2": {
+ "text": "moving",
+ "color": "blue"
+ }
+ }
+ }
+ ],
+ "color": {
+ "mode": "fixed",
+ "fixedColor": "transparent"
+ }
+ },
+ "overrides": []
+ },
+ "options": {
+ "showValue": "never",
+ "rowHeight": 0.8,
+ "mergeValues": true,
+ "legend": {
+ "showLegend": false
+ },
+ "alignValue": "left"
+ },
+ "pluginVersion": "11.2.0"
+ },
+ {
+ "type": "timeseries",
+ "title": "Drive board temperature",
+ "description": "EPOS4 power stage temperature; motion is shaded",
+ "id": 9,
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "gridPos": {
+ "h": 9,
+ "w": 12,
+ "x": 0,
+ "y": 15
+ },
+ "targets": [
+ {
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "query": "import \"regexp\"\nimport \"strings\"\nfrom(bucket: \"LRIS2\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r.peer == \"csu\" and r._measurement =~ /^boardtemp[0-9]+$/)\n |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)\n |> map(fn: (r) => ({_time: r._time, _value: r._value, _field: \"CSU-\" + (if strings.strlen(v: regexp.replaceAllString(r: /^[a-z0-9]*[a-z]/, v: r._measurement, t: \"\")) == 1 then \"0\" else \"\") + regexp.replaceAllString(r: /^[a-z0-9]*[a-z]/, v: r._measurement, t: \"\")}))\n |> group(columns: [\"_field\"])\n |> sort(columns: [\"_time\"])",
+ "refId": "A"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "unit": "celsius",
+ "custom": {
+ "lineWidth": 1,
+ "fillOpacity": 0,
+ "showPoints": "never",
+ "spanNulls": true
+ },
+ "displayName": "${__field.labels._field}"
+ },
+ "overrides": []
+ },
+ "options": {
+ "legend": {
+ "displayMode": "table",
+ "placement": "right",
+ "calcs": [
+ "lastNotNull",
+ "max"
+ ],
+ "sortBy": "Last *",
+ "sortDesc": true
+ },
+ "tooltip": {
+ "mode": "multi",
+ "sort": "desc"
+ }
+ },
+ "pluginVersion": "11.2.0"
+ },
+ {
+ "type": "timeseries",
+ "title": "Motor I2t",
+ "description": "Drive thermal model of the motor winding; 100 % trips the drive",
+ "id": 10,
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "gridPos": {
+ "h": 9,
+ "w": 12,
+ "x": 12,
+ "y": 15
+ },
+ "targets": [
+ {
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "query": "import \"regexp\"\nimport \"strings\"\nfrom(bucket: \"LRIS2\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r.peer == \"csu\" and r._measurement =~ /^i2tmotor[0-9]+$/)\n |> aggregateWindow(every: v.windowPeriod, fn: max, createEmpty: false)\n |> map(fn: (r) => ({_time: r._time, _value: r._value, _field: \"CSU-\" + (if strings.strlen(v: regexp.replaceAllString(r: /^[a-z0-9]*[a-z]/, v: r._measurement, t: \"\")) == 1 then \"0\" else \"\") + regexp.replaceAllString(r: /^[a-z0-9]*[a-z]/, v: r._measurement, t: \"\")}))\n |> group(columns: [\"_field\"])\n |> sort(columns: [\"_time\"])",
+ "refId": "A"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "unit": "percent",
+ "custom": {
+ "lineWidth": 1,
+ "fillOpacity": 0,
+ "showPoints": "never",
+ "spanNulls": true
+ },
+ "displayName": "${__field.labels._field}"
+ },
+ "overrides": []
+ },
+ "options": {
+ "legend": {
+ "displayMode": "table",
+ "placement": "right",
+ "calcs": [
+ "lastNotNull",
+ "max"
+ ],
+ "sortBy": "Last *",
+ "sortDesc": true
+ },
+ "tooltip": {
+ "mode": "multi",
+ "sort": "desc"
+ }
+ },
+ "pluginVersion": "11.2.0"
+ },
+ {
+ "type": "timeseries",
+ "title": "Motor current",
+ "description": "",
+ "id": 11,
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "gridPos": {
+ "h": 8,
+ "w": 8,
+ "x": 0,
+ "y": 24
+ },
+ "targets": [
+ {
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "query": "import \"regexp\"\nimport \"strings\"\nfrom(bucket: \"LRIS2\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r.peer == \"csu\" and r._measurement =~ /^current[0-9]+$/)\n |> aggregateWindow(every: v.windowPeriod, fn: max, createEmpty: false)\n |> map(fn: (r) => ({_time: r._time, _value: r._value, _field: \"CSU-\" + (if strings.strlen(v: regexp.replaceAllString(r: /^[a-z0-9]*[a-z]/, v: r._measurement, t: \"\")) == 1 then \"0\" else \"\") + regexp.replaceAllString(r: /^[a-z0-9]*[a-z]/, v: r._measurement, t: \"\")}))\n |> group(columns: [\"_field\"])\n |> sort(columns: [\"_time\"])",
+ "refId": "A"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "unit": "mamp",
+ "custom": {
+ "lineWidth": 1,
+ "fillOpacity": 0,
+ "showPoints": "never",
+ "spanNulls": true
+ },
+ "displayName": "${__field.labels._field}"
+ },
+ "overrides": []
+ },
+ "options": {
+ "legend": {
+ "displayMode": "table",
+ "placement": "right",
+ "calcs": [
+ "lastNotNull",
+ "max"
+ ],
+ "sortBy": "Last *",
+ "sortDesc": true
+ },
+ "tooltip": {
+ "mode": "multi",
+ "sort": "desc"
+ }
+ },
+ "pluginVersion": "11.2.0"
+ },
+ {
+ "type": "timeseries",
+ "title": "Power stage I2t",
+ "description": "",
+ "id": 12,
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "gridPos": {
+ "h": 8,
+ "w": 8,
+ "x": 8,
+ "y": 24
+ },
+ "targets": [
+ {
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "query": "import \"regexp\"\nimport \"strings\"\nfrom(bucket: \"LRIS2\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r.peer == \"csu\" and r._measurement =~ /^i2tstage[0-9]+$/)\n |> aggregateWindow(every: v.windowPeriod, fn: max, createEmpty: false)\n |> map(fn: (r) => ({_time: r._time, _value: r._value, _field: \"CSU-\" + (if strings.strlen(v: regexp.replaceAllString(r: /^[a-z0-9]*[a-z]/, v: r._measurement, t: \"\")) == 1 then \"0\" else \"\") + regexp.replaceAllString(r: /^[a-z0-9]*[a-z]/, v: r._measurement, t: \"\")}))\n |> group(columns: [\"_field\"])\n |> sort(columns: [\"_time\"])",
+ "refId": "A"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "unit": "percent",
+ "custom": {
+ "lineWidth": 1,
+ "fillOpacity": 0,
+ "showPoints": "never",
+ "spanNulls": true
+ },
+ "displayName": "${__field.labels._field}"
+ },
+ "overrides": []
+ },
+ "options": {
+ "legend": {
+ "displayMode": "table",
+ "placement": "right",
+ "calcs": [
+ "lastNotNull",
+ "max"
+ ],
+ "sortBy": "Last *",
+ "sortDesc": true
+ },
+ "tooltip": {
+ "mode": "multi",
+ "sort": "desc"
+ }
+ },
+ "pluginVersion": "11.2.0"
+ },
+ {
+ "type": "timeseries",
+ "title": "Drive supply",
+ "description": "",
+ "id": 13,
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "gridPos": {
+ "h": 8,
+ "w": 8,
+ "x": 16,
+ "y": 24
+ },
+ "targets": [
+ {
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "query": "import \"regexp\"\nimport \"strings\"\nfrom(bucket: \"LRIS2\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r.peer == \"csu\" and r._measurement =~ /^supply[0-9]+$/)\n |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)\n |> map(fn: (r) => ({_time: r._time, _value: r._value, _field: \"CSU-\" + (if strings.strlen(v: regexp.replaceAllString(r: /^[a-z0-9]*[a-z]/, v: r._measurement, t: \"\")) == 1 then \"0\" else \"\") + regexp.replaceAllString(r: /^[a-z0-9]*[a-z]/, v: r._measurement, t: \"\")}))\n |> group(columns: [\"_field\"])\n |> sort(columns: [\"_time\"])",
+ "refId": "A"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "unit": "volt",
+ "custom": {
+ "lineWidth": 1,
+ "fillOpacity": 0,
+ "showPoints": "never",
+ "spanNulls": true
+ },
+ "displayName": "${__field.labels._field}"
+ },
+ "overrides": []
+ },
+ "options": {
+ "legend": {
+ "displayMode": "table",
+ "placement": "right",
+ "calcs": [
+ "lastNotNull",
+ "max"
+ ],
+ "sortBy": "Last *",
+ "sortDesc": true
+ },
+ "tooltip": {
+ "mode": "multi",
+ "sort": "desc"
+ }
+ },
+ "pluginVersion": "11.2.0"
+ },
+ {
+ "type": "row",
+ "title": "Power (${pdu})",
+ "collapsed": false,
+ "panels": [],
+ "id": 14,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 32
+ },
+ "pluginVersion": "11.2.0"
+ },
+ {
+ "type": "state-timeline",
+ "title": "Outlet state",
+ "description": "",
+ "id": 15,
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 24,
+ "x": 0,
+ "y": 33
+ },
+ "targets": [
+ {
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "query": "import \"regexp\"\nimport \"strings\"\nfrom(bucket: \"LRIS2\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r.peer =~ /^${pdu:regex}$/ and r._measurement =~ /^state(_[A-Za-z0-9_]+|[0-9]+)$/)\n |> map(fn: (r) => ({_time: r._time, _value: if r._value then 1 else 0, _field: r.peer + \" \" + r._measurement}))\n |> group(columns: [\"_field\"])\n |> sort(columns: [\"_time\"])\n |> aggregateWindow(every: v.windowPeriod, fn: max, createEmpty: false)",
+ "refId": "A"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "displayName": "${__field.labels._field}",
+ "custom": {
+ "fillOpacity": 80,
+ "lineWidth": 0
+ },
+ "mappings": [
+ {
+ "type": "value",
+ "options": {
+ "0": {
+ "text": "no",
+ "color": "transparent"
+ },
+ "1": {
+ "text": "on",
+ "color": "green"
+ }
+ }
+ }
+ ],
+ "color": {
+ "mode": "fixed",
+ "fixedColor": "transparent"
+ }
+ },
+ "overrides": []
+ },
+ "options": {
+ "showValue": "never",
+ "rowHeight": 0.8,
+ "mergeValues": true,
+ "legend": {
+ "showLegend": false
+ },
+ "alignValue": "left"
+ },
+ "pluginVersion": "11.2.0"
+ },
+ {
+ "type": "timeseries",
+ "title": "Power per outlet",
+ "description": "",
+ "id": 16,
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "gridPos": {
+ "h": 9,
+ "w": 12,
+ "x": 0,
+ "y": 40
+ },
+ "targets": [
+ {
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "query": "import \"regexp\"\nimport \"strings\"\nfrom(bucket: \"LRIS2\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r.peer =~ /^${pdu:regex}$/ and r._measurement =~ /^power(_[A-Za-z0-9_]+|[0-9]+)$/)\n |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)\n |> map(fn: (r) => ({_time: r._time, _value: r._value, _field: r.peer + \" \" + r._measurement}))\n |> group(columns: [\"_field\"])\n |> sort(columns: [\"_time\"])",
+ "refId": "A"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "unit": "watt",
+ "custom": {
+ "lineWidth": 1,
+ "fillOpacity": 10,
+ "showPoints": "never",
+ "spanNulls": true,
+ "stacking": {
+ "mode": "normal",
+ "group": "A"
+ }
+ },
+ "displayName": "${__field.labels._field}"
+ },
+ "overrides": []
+ },
+ "options": {
+ "legend": {
+ "displayMode": "table",
+ "placement": "right",
+ "calcs": [
+ "lastNotNull",
+ "max"
+ ],
+ "sortBy": "Last *",
+ "sortDesc": true
+ },
+ "tooltip": {
+ "mode": "multi",
+ "sort": "desc"
+ }
+ },
+ "pluginVersion": "11.2.0"
+ },
+ {
+ "type": "timeseries",
+ "title": "Current per outlet",
+ "description": "",
+ "id": 17,
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "gridPos": {
+ "h": 9,
+ "w": 12,
+ "x": 12,
+ "y": 40
+ },
+ "targets": [
+ {
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "query": "import \"regexp\"\nimport \"strings\"\nfrom(bucket: \"LRIS2\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r.peer =~ /^${pdu:regex}$/ and r._measurement =~ /^current(_[A-Za-z0-9_]+|[0-9]+)$/)\n |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)\n |> map(fn: (r) => ({_time: r._time, _value: r._value, _field: r.peer + \" \" + r._measurement}))\n |> group(columns: [\"_field\"])\n |> sort(columns: [\"_time\"])",
+ "refId": "A"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "unit": "amp",
+ "custom": {
+ "lineWidth": 1,
+ "fillOpacity": 0,
+ "showPoints": "never",
+ "spanNulls": true
+ },
+ "displayName": "${__field.labels._field}"
+ },
+ "overrides": []
+ },
+ "options": {
+ "legend": {
+ "displayMode": "table",
+ "placement": "right",
+ "calcs": [
+ "lastNotNull",
+ "max"
+ ],
+ "sortBy": "Last *",
+ "sortDesc": true
+ },
+ "tooltip": {
+ "mode": "multi",
+ "sort": "desc"
+ }
+ },
+ "pluginVersion": "11.2.0"
+ },
+ {
+ "type": "timeseries",
+ "title": "Energy per outlet",
+ "description": "",
+ "id": 18,
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "gridPos": {
+ "h": 8,
+ "w": 24,
+ "x": 0,
+ "y": 49
+ },
+ "targets": [
+ {
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "query": "import \"regexp\"\nimport \"strings\"\nfrom(bucket: \"LRIS2\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r.peer =~ /^${pdu:regex}$/ and r._measurement =~ /^energy(_[A-Za-z0-9_]+|[0-9]+)$/)\n |> aggregateWindow(every: v.windowPeriod, fn: last, createEmpty: false)\n |> map(fn: (r) => ({_time: r._time, _value: r._value, _field: r.peer + \" \" + r._measurement}))\n |> group(columns: [\"_field\"])\n |> sort(columns: [\"_time\"])",
+ "refId": "A"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "unit": "watth",
+ "custom": {
+ "lineWidth": 1,
+ "fillOpacity": 0,
+ "showPoints": "never",
+ "spanNulls": true
+ },
+ "displayName": "${__field.labels._field}"
+ },
+ "overrides": []
+ },
+ "options": {
+ "legend": {
+ "displayMode": "table",
+ "placement": "right",
+ "calcs": [
+ "lastNotNull",
+ "max"
+ ],
+ "sortBy": "Last *",
+ "sortDesc": true
+ },
+ "tooltip": {
+ "mode": "multi",
+ "sort": "desc"
+ }
+ },
+ "pluginVersion": "11.2.0"
+ },
+ {
+ "type": "row",
+ "title": "Thermovac",
+ "collapsed": false,
+ "panels": [],
+ "id": 19,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 57
+ },
+ "pluginVersion": "11.2.0"
+ },
+ {
+ "type": "timeseries",
+ "title": "Pressure",
+ "description": "",
+ "id": 20,
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "gridPos": {
+ "h": 9,
+ "w": 12,
+ "x": 0,
+ "y": 58
+ },
+ "targets": [
+ {
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "query": "import \"regexp\"\nimport \"strings\"\nfrom(bucket: \"LRIS2\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r.peer == \"rpress\" and r._measurement =~ /^pressure[0-9]+$/)\n |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)\n |> map(fn: (r) => ({_time: r._time, _value: r._value, _field: r._measurement}))\n |> group(columns: [\"_field\"])\n |> sort(columns: [\"_time\"])",
+ "refId": "A"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "unit": "pressurembar",
+ "custom": {
+ "lineWidth": 1,
+ "fillOpacity": 0,
+ "showPoints": "never",
+ "spanNulls": true,
+ "scaleDistribution": {
+ "type": "log",
+ "log": 10
+ }
+ },
+ "displayName": "${__field.labels._field}"
+ },
+ "overrides": []
+ },
+ "options": {
+ "legend": {
+ "displayMode": "table",
+ "placement": "right",
+ "calcs": [
+ "lastNotNull",
+ "max"
+ ],
+ "sortBy": "Last *",
+ "sortDesc": true
+ },
+ "tooltip": {
+ "mode": "multi",
+ "sort": "desc"
+ }
+ },
+ "pluginVersion": "11.2.0"
+ },
+ {
+ "type": "timeseries",
+ "title": "Cryocooler",
+ "description": "",
+ "id": 21,
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "gridPos": {
+ "h": 9,
+ "w": 12,
+ "x": 12,
+ "y": 58
+ },
+ "targets": [
+ {
+ "datasource": {
+ "type": "influxdb",
+ "uid": "edy7o8tiy9s00e"
+ },
+ "query": "import \"regexp\"\nimport \"strings\"\nfrom(bucket: \"LRIS2\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r.peer == \"rcryo\" and r._measurement =~ /^(coldtemp|rejecttemp|curcmdpower)$/)\n |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)\n |> map(fn: (r) => ({_time: r._time, _value: r._value, _field: r._measurement}))\n |> group(columns: [\"_field\"])\n |> sort(columns: [\"_time\"])",
+ "refId": "A"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "unit": "none",
+ "custom": {
+ "lineWidth": 1,
+ "fillOpacity": 0,
+ "showPoints": "never",
+ "spanNulls": true
+ },
+ "displayName": "${__field.labels._field}"
+ },
+ "overrides": []
+ },
+ "options": {
+ "legend": {
+ "displayMode": "table",
+ "placement": "right",
+ "calcs": [
+ "lastNotNull",
+ "max"
+ ],
+ "sortBy": "Last *",
+ "sortDesc": true
+ },
+ "tooltip": {
+ "mode": "multi",
+ "sort": "desc"
+ }
+ },
+ "pluginVersion": "11.2.0"
+ }
+ ],
+ "refresh": "1m",
+ "schemaVersion": 39,
+ "tags": [
+ "lris2",
+ "telemetry"
+ ],
+ "templating": {
+ "list": [
+ {
+ "type": "custom",
+ "name": "pdu",
+ "label": "PDU",
+ "query": "pdu-137,pdu-ethercat",
+ "multi": true,
+ "includeAll": true,
+ "current": {
+ "selected": true,
+ "text": [
+ "All"
+ ],
+ "value": [
+ "$__all"
+ ]
+ },
+ "options": [
+ {
+ "selected": true,
+ "text": "All",
+ "value": "$__all"
+ },
+ {
+ "selected": false,
+ "text": "pdu-137",
+ "value": "pdu-137"
+ },
+ {
+ "selected": false,
+ "text": "pdu-ethercat",
+ "value": "pdu-ethercat"
+ }
+ ]
+ }
+ ]
+ },
+ "time": {
+ "from": "now-6h",
+ "to": "now"
+ },
+ "timepicker": {},
+ "timezone": "browser",
+ "title": "LRIS2",
+ "uid": "lris2-general",
+ "weekStart": ""
+}
\ No newline at end of file
diff --git a/grafana/lris2-power-dashboard.json b/grafana/lris2-power-dashboard.json
deleted file mode 100644
index a8cf4fc..0000000
--- a/grafana/lris2-power-dashboard.json
+++ /dev/null
@@ -1,522 +0,0 @@
-{
- "annotations": {
- "list": [
- {
- "builtIn": 1,
- "datasource": {
- "type": "grafana",
- "uid": "-- Grafana --"
- },
- "enable": true,
- "hide": true,
- "iconColor": "rgba(0, 211, 255, 1)",
- "name": "Annotations & Alerts",
- "type": "dashboard"
- }
- ]
- },
- "editable": true,
- "fiscalYearStartMonth": 0,
- "graphTooltip": 1,
- "links": [],
- "liveNow": false,
- "panels": [
- {
- "collapsed": false,
- "panels": [],
- "title": "PDU 1: Eaton EMAT-08 (l2power.pdu1)",
- "type": "row",
- "id": 1,
- "gridPos": {
- "h": 1,
- "w": 24,
- "x": 0,
- "y": 0
- }
- },
- {
- "datasource": {
- "type": "influxdb",
- "uid": "edy7o8tiy9s00e"
- },
- "description": "",
- "fieldConfig": {
- "defaults": {
- "color": {
- "mode": "thresholds"
- },
- "displayName": "${__field.labels._field}",
- "mappings": [],
- "thresholds": {
- "mode": "absolute",
- "steps": [
- {
- "color": "green",
- "value": null
- },
- {
- "color": "yellow",
- "value": 90
- },
- {
- "color": "red",
- "value": 300
- }
- ]
- },
- "unit": "s",
- "decimals": 0
- },
- "overrides": []
- },
- "options": {
- "colorMode": "background",
- "graphMode": "none",
- "justifyMode": "auto",
- "orientation": "auto",
- "reduceOptions": {
- "calcs": [
- "lastNotNull"
- ],
- "fields": "",
- "values": false
- },
- "textMode": "auto",
- "wideLayout": true
- },
- "pluginVersion": "11.2.0",
- "targets": [
- {
- "datasource": {
- "type": "influxdb",
- "uid": "edy7o8tiy9s00e"
- },
- "query": "from(bucket: \"LRIS2\")\n |> range(start: -7d)\n |> filter(fn: (r) => r.peer == \"pdu1\" and r._measurement == \"power1\")\n |> last()\n |> map(fn: (r) => ({_time: r._time, _field: \"pdu1\", _value: float(v: int(v: now()) - int(v: r._time)) / 1000000000.0}))",
- "refId": "A"
- }
- ],
- "title": "Last pdu1 sample",
- "type": "stat",
- "id": 2,
- "gridPos": {
- "h": 4,
- "w": 4,
- "x": 0,
- "y": 1
- }
- },
- {
- "datasource": {
- "type": "influxdb",
- "uid": "edy7o8tiy9s00e"
- },
- "description": "",
- "fieldConfig": {
- "defaults": {
- "color": {
- "mode": "thresholds"
- },
- "displayName": "${__field.labels._field}",
- "mappings": [],
- "thresholds": {
- "mode": "absolute",
- "steps": [
- {
- "color": "blue",
- "value": null
- }
- ]
- },
- "unit": "watt"
- },
- "overrides": []
- },
- "options": {
- "colorMode": "value",
- "graphMode": "none",
- "justifyMode": "auto",
- "orientation": "auto",
- "reduceOptions": {
- "calcs": [
- "lastNotNull"
- ],
- "fields": "",
- "values": false
- },
- "textMode": "auto",
- "wideLayout": true
- },
- "pluginVersion": "11.2.0",
- "targets": [
- {
- "datasource": {
- "type": "influxdb",
- "uid": "edy7o8tiy9s00e"
- },
- "query": "from(bucket: \"LRIS2\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r.peer == \"pdu1\" and r._measurement =~ /^power[0-9]+$/)\n |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)\n |> group()\n |> aggregateWindow(every: v.windowPeriod, fn: sum, createEmpty: false)\n |> map(fn: (r) => ({r with _field: \"total\"}))",
- "refId": "A"
- }
- ],
- "title": "Total power",
- "type": "stat",
- "id": 3,
- "gridPos": {
- "h": 4,
- "w": 4,
- "x": 4,
- "y": 1
- }
- },
- {
- "datasource": {
- "type": "influxdb",
- "uid": "edy7o8tiy9s00e"
- },
- "description": "",
- "fieldConfig": {
- "defaults": {
- "color": {
- "mode": "thresholds"
- },
- "displayName": "${__field.labels._field}",
- "mappings": [],
- "thresholds": {
- "mode": "absolute",
- "steps": [
- {
- "color": "blue",
- "value": null
- }
- ]
- },
- "unit": "none"
- },
- "overrides": []
- },
- "options": {
- "colorMode": "value",
- "graphMode": "none",
- "justifyMode": "auto",
- "orientation": "auto",
- "reduceOptions": {
- "calcs": [
- "lastNotNull"
- ],
- "fields": "",
- "values": false
- },
- "textMode": "auto",
- "wideLayout": true
- },
- "pluginVersion": "11.2.0",
- "targets": [
- {
- "datasource": {
- "type": "influxdb",
- "uid": "edy7o8tiy9s00e"
- },
- "query": "from(bucket: \"LRIS2\")\n |> range(start: -1h)\n |> filter(fn: (r) => r.peer == \"pdu1\" and r._measurement =~ /^state[0-9]+$/)\n |> last()\n |> map(fn: (r) => ({r with _value: if r._value then 1 else 0}))\n |> group()\n |> sum()\n |> map(fn: (r) => ({r with _field: \"on\"}))",
- "refId": "A"
- }
- ],
- "title": "Outlets on",
- "type": "stat",
- "id": 4,
- "gridPos": {
- "h": 4,
- "w": 4,
- "x": 8,
- "y": 1
- }
- },
- {
- "datasource": {
- "type": "influxdb",
- "uid": "edy7o8tiy9s00e"
- },
- "description": "",
- "fieldConfig": {
- "defaults": {
- "color": {
- "mode": "thresholds"
- },
- "displayName": "${__field.labels._field}",
- "mappings": [],
- "thresholds": {
- "mode": "absolute",
- "steps": [
- {
- "color": "blue",
- "value": null
- }
- ]
- },
- "unit": "watth"
- },
- "overrides": []
- },
- "options": {
- "colorMode": "value",
- "graphMode": "none",
- "justifyMode": "auto",
- "orientation": "auto",
- "reduceOptions": {
- "calcs": [
- "lastNotNull"
- ],
- "fields": "/.*/",
- "values": false
- },
- "textMode": "value_and_name",
- "wideLayout": true
- },
- "pluginVersion": "11.2.0",
- "targets": [
- {
- "datasource": {
- "type": "influxdb",
- "uid": "edy7o8tiy9s00e"
- },
- "query": "import \"strings\"\nfrom(bucket: \"LRIS2\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r.peer == \"pdu1\" and r._measurement =~ /^energy[0-9]+$/)\n |> last()\n |> map(fn: (r) => ({r with _field: strings.trimSuffix(v: strings.trimPrefix(v: r._measurement, prefix: \"energy\"), suffix: \"\")}))\n |> keep(columns: [\"_time\", \"_value\", \"_field\"])\n |> group(columns: [\"_field\"])",
- "refId": "A"
- }
- ],
- "title": "Energy since reset",
- "type": "stat",
- "id": 5,
- "gridPos": {
- "h": 4,
- "w": 12,
- "x": 12,
- "y": 1
- }
- },
- {
- "datasource": {
- "type": "influxdb",
- "uid": "edy7o8tiy9s00e"
- },
- "description": "",
- "fieldConfig": {
- "defaults": {
- "color": {
- "mode": "thresholds"
- },
- "custom": {
- "fillOpacity": 70,
- "lineWidth": 0
- },
- "displayName": "${__field.labels._field}",
- "mappings": [
- {
- "type": "value",
- "options": {
- "0": {
- "color": "dark-gray",
- "text": "OFF"
- },
- "1": {
- "color": "green",
- "text": "ON"
- }
- }
- }
- ],
- "thresholds": {
- "mode": "absolute",
- "steps": [
- {
- "color": "dark-gray",
- "value": null
- },
- {
- "color": "green",
- "value": 1
- }
- ]
- }
- },
- "overrides": []
- },
- "options": {
- "alignValue": "left",
- "mergeValues": true,
- "rowHeight": 0.8,
- "showValue": "auto",
- "legend": {
- "showLegend": false
- },
- "tooltip": {
- "mode": "single",
- "sort": "none"
- }
- },
- "targets": [
- {
- "datasource": {
- "type": "influxdb",
- "uid": "edy7o8tiy9s00e"
- },
- "query": "import \"strings\"\nfrom(bucket: \"LRIS2\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r.peer == \"pdu1\" and r._measurement =~ /^state[0-9]+$/)\n |> map(fn: (r) => ({r with _value: if r._value then 1 else 0}))\n |> aggregateWindow(every: v.windowPeriod, fn: last, createEmpty: false)\n |> map(fn: (r) => ({r with _field: strings.trimSuffix(v: strings.trimPrefix(v: r._measurement, prefix: \"state\"), suffix: \"\")}))\n |> keep(columns: [\"_time\", \"_value\", \"_field\"])\n |> group(columns: [\"_field\"])",
- "refId": "A"
- }
- ],
- "title": "Outlet state",
- "type": "state-timeline",
- "id": 6,
- "gridPos": {
- "h": 7,
- "w": 24,
- "x": 0,
- "y": 5
- }
- },
- {
- "datasource": {
- "type": "influxdb",
- "uid": "edy7o8tiy9s00e"
- },
- "description": "",
- "fieldConfig": {
- "defaults": {
- "color": {
- "mode": "palette-classic"
- },
- "custom": {
- "drawStyle": "line",
- "fillOpacity": 20,
- "lineWidth": 1,
- "showPoints": "never",
- "spanNulls": true,
- "stacking": {
- "group": "A",
- "mode": "normal"
- }
- },
- "displayName": "${__field.labels._field}",
- "unit": "watt",
- "min": 0
- },
- "overrides": []
- },
- "options": {
- "legend": {
- "calcs": [
- "lastNotNull",
- "min",
- "max"
- ],
- "displayMode": "table",
- "placement": "right",
- "showLegend": true
- },
- "tooltip": {
- "mode": "multi",
- "sort": "none"
- }
- },
- "targets": [
- {
- "datasource": {
- "type": "influxdb",
- "uid": "edy7o8tiy9s00e"
- },
- "query": "import \"strings\"\nfrom(bucket: \"LRIS2\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r.peer == \"pdu1\" and r._measurement =~ /^power[0-9]+$/)\n |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)\n |> map(fn: (r) => ({r with _field: strings.trimSuffix(v: strings.trimPrefix(v: r._measurement, prefix: \"power\"), suffix: \"\")}))\n |> keep(columns: [\"_time\", \"_value\", \"_field\"])\n |> group(columns: [\"_field\"])",
- "refId": "A"
- }
- ],
- "title": "Power per outlet",
- "type": "timeseries",
- "id": 7,
- "gridPos": {
- "h": 9,
- "w": 12,
- "x": 0,
- "y": 12
- }
- },
- {
- "datasource": {
- "type": "influxdb",
- "uid": "edy7o8tiy9s00e"
- },
- "description": "",
- "fieldConfig": {
- "defaults": {
- "color": {
- "mode": "palette-classic"
- },
- "custom": {
- "drawStyle": "line",
- "fillOpacity": 0,
- "lineWidth": 1,
- "showPoints": "never",
- "spanNulls": true,
- "stacking": {
- "group": "A",
- "mode": "none"
- }
- },
- "displayName": "${__field.labels._field}",
- "unit": "amp",
- "min": 0
- },
- "overrides": []
- },
- "options": {
- "legend": {
- "calcs": [
- "lastNotNull",
- "min",
- "max"
- ],
- "displayMode": "table",
- "placement": "right",
- "showLegend": true
- },
- "tooltip": {
- "mode": "multi",
- "sort": "none"
- }
- },
- "targets": [
- {
- "datasource": {
- "type": "influxdb",
- "uid": "edy7o8tiy9s00e"
- },
- "query": "import \"strings\"\nfrom(bucket: \"LRIS2\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r.peer == \"pdu1\" and r._measurement =~ /^current[0-9]+$/)\n |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)\n |> map(fn: (r) => ({r with _field: strings.trimSuffix(v: strings.trimPrefix(v: r._measurement, prefix: \"current\"), suffix: \"\")}))\n |> keep(columns: [\"_time\", \"_value\", \"_field\"])\n |> group(columns: [\"_field\"])",
- "refId": "A"
- }
- ],
- "title": "Current per outlet",
- "type": "timeseries",
- "id": 8,
- "gridPos": {
- "h": 9,
- "w": 12,
- "x": 12,
- "y": 12
- }
- }
- ],
- "refresh": "1m",
- "schemaVersion": 39,
- "tags": [
- "lris2",
- "power",
- "telemetry"
- ],
- "templating": {
- "list": []
- },
- "time": {
- "from": "now-6h",
- "to": "now"
- },
- "timepicker": {},
- "timezone": "browser",
- "title": "LRIS2 Power",
- "uid": "lris2-power",
- "weekStart": ""
-}
diff --git a/plc/csu-motion-server/E_MoveMode.TcDUT b/plc/csu-motion-server/E_MoveMode.TcDUT
new file mode 100644
index 0000000..cf57c97
--- /dev/null
+++ b/plc/csu-motion-server/E_MoveMode.TcDUT
@@ -0,0 +1,13 @@
+
+
+
+
+
+
diff --git a/plc/csu-motion-server/FB_AxisServer.TcPOU b/plc/csu-motion-server/FB_AxisServer.TcPOU
new file mode 100644
index 0000000..bc61278
--- /dev/null
+++ b/plc/csu-motion-server/FB_AxisServer.TcPOU
@@ -0,0 +1,125 @@
+
+
+
+
+
+
+
+
+
diff --git a/plc/csu-motion-server/GVL_Axes.TcGVL b/plc/csu-motion-server/GVL_Axes.TcGVL
new file mode 100644
index 0000000..fa62e0e
--- /dev/null
+++ b/plc/csu-motion-server/GVL_Axes.TcGVL
@@ -0,0 +1,13 @@
+
+
+
+ NC Axis 1 -> CSU-0
+END_VAR
+]]>
+
+
diff --git a/plc/csu-motion-server/MAIN.TcPOU b/plc/csu-motion-server/MAIN.TcPOU
new file mode 100644
index 0000000..ae7a434
--- /dev/null
+++ b/plc/csu-motion-server/MAIN.TcPOU
@@ -0,0 +1,17 @@
+
+
+
+
+
+
+
+
+
diff --git a/plc/csu-motion-server/ST_Axis.TcDUT b/plc/csu-motion-server/ST_Axis.TcDUT
new file mode 100644
index 0000000..cc9dbf9
--- /dev/null
+++ b/plc/csu-motion-server/ST_Axis.TcDUT
@@ -0,0 +1,12 @@
+
+
+
+
+
+
diff --git a/plc/csu-motion-server/ST_AxisCmd.TcDUT b/plc/csu-motion-server/ST_AxisCmd.TcDUT
new file mode 100644
index 0000000..b1f67e8
--- /dev/null
+++ b/plc/csu-motion-server/ST_AxisCmd.TcDUT
@@ -0,0 +1,20 @@
+
+
+
+
+
+
diff --git a/plc/csu-motion-server/ST_AxisSts.TcDUT b/plc/csu-motion-server/ST_AxisSts.TcDUT
new file mode 100644
index 0000000..5e8481f
--- /dev/null
+++ b/plc/csu-motion-server/ST_AxisSts.TcDUT
@@ -0,0 +1,20 @@
+
+
+
+
+
+
diff --git a/plc/setup-csu.ps1 b/plc/setup-csu.ps1
new file mode 100644
index 0000000..767f831
--- /dev/null
+++ b/plc/setup-csu.ps1
@@ -0,0 +1,98 @@
+<#
+.SYNOPSIS
+Install the CSU motion server into a TwinCAT project through the Automation Interface.
+
+.DESCRIPTION
+Opens the solution in a hidden TcXaeShell, replaces the PLC project's objects with
+the sources in csu-motion-server, builds, links GVL_Axes.AxisRef[N] to NC Axis N,
+and saves. With -Activate it also activates the configuration and starts the PLC
+with its boot project. Close TcXaeShell before running; both would edit the same files.
+#>
+param(
+ [Parameter(Mandatory)] [string] $Solution,
+ [string] $PlcProject = "Untitled1",
+ [int] $AxisCount = 23,
+ [switch] $Activate
+)
+$ErrorActionPreference = "Stop"
+$sources = Join-Path $PSScriptRoot "csu-motion-server"
+$importOrder = "E_MoveMode", "ST_AxisCmd", "ST_AxisSts", "ST_Axis", "GVL_Axes", "FB_AxisServer", "MAIN"
+$folderFor = @{ ".TcDUT" = "DUTs"; ".TcGVL" = "GVLs"; ".TcPOU" = "POUs" }
+$existingItem = 58
+
+# TcXaeShell rejects COM calls while busy; this filter retries them
+Add-Type -TypeDefinition @"
+using System;
+using System.Runtime.InteropServices;
+[ComImport, Guid("00000016-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+public interface IOleMessageFilter {
+ [PreserveSig] int HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo);
+ [PreserveSig] int RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType);
+ [PreserveSig] int MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType);
+}
+public class MessageFilter : IOleMessageFilter {
+ [DllImport("Ole32.dll")] static extern int CoRegisterMessageFilter(IOleMessageFilter newFilter, out IOleMessageFilter oldFilter);
+ public static void Register() { IOleMessageFilter old; CoRegisterMessageFilter(new MessageFilter(), out old); }
+ public static void Revoke() { IOleMessageFilter old; CoRegisterMessageFilter(null, out old); }
+ int IOleMessageFilter.HandleInComingCall(int a, IntPtr b, int c, IntPtr d) { return 0; }
+ int IOleMessageFilter.RetryRejectedCall(IntPtr a, int tick, int type) { return type == 2 && tick < 120000 ? 200 : -1; }
+ int IOleMessageFilter.MessagePending(IntPtr a, int b, int c) { return 2; }
+}
+"@
+
+function Import-Sources($sys, $base) {
+ $pous = $sys.LookupTreeItem("$base^POUs")
+ for ($i = $pous.ChildCount; $i -ge 1; $i--) { $pous.DeleteChild($pous.Child($i).Name) }
+ foreach ($name in $importOrder) {
+ $file = Get-ChildItem $sources -Filter "$name.*"
+ $folder = $sys.LookupTreeItem("$base^" + $folderFor[$file.Extension])
+ try { $folder.DeleteChild($name) } catch [System.Runtime.InteropServices.COMException] { }
+ Write-Output ("imported " + $folder.CreateChild($name, $existingItem, $null, $file.FullName).PathName)
+ }
+}
+
+function Assert-BuildClean($dte) {
+ $dte.Solution.SolutionBuild.Build($true)
+ $errors = @($dte.ToolWindows.ErrorList.ErrorItems | ForEach-Object { $_ } | Where-Object { $_.ErrorLevel -eq 2 })
+ $errors | ForEach-Object { Write-Output (" " + $_.FileName + ":" + $_.Line + " " + $_.Description) }
+ if ($errors.Count -gt 0) { throw "build failed with $($errors.Count) errors; nothing linked or saved" }
+ Write-Output "build clean"
+}
+
+function Connect-Axes($sys, $instance) {
+ for ($n = 1; $n -le $AxisCount; $n++) {
+ $axis = "TINC^NC-Task 1 SAF^Axes^Axis $n"
+ $sys.LinkVariables("$instance^PlcTask Inputs^GVL_Axes.AxisRef[$n].NcToPlc", "$axis^Outputs^ToPlc")
+ $sys.LinkVariables("$instance^PlcTask Outputs^GVL_Axes.AxisRef[$n].PlcToNc", "$axis^Inputs^FromPlc")
+ }
+ Write-Output "linked AxisRef[1..$AxisCount] to NC Axis 1..$AxisCount"
+}
+
+[MessageFilter]::Register()
+$dte = $null
+try {
+ $dte = New-Object -ComObject "TcXaeShell.DTE.15.0"
+ $dte.SuppressUI = $true
+ $dte.Solution.Open((Resolve-Path $Solution).Path)
+ $sys = $dte.Solution.Projects.Item(1).Object
+ $base = "TIPC^$PlcProject^$PlcProject Project"
+
+ Import-Sources $sys $base
+ Assert-BuildClean $dte
+ Connect-Axes $sys "TIPC^$PlcProject^$PlcProject Instance"
+ $dte.ExecuteCommand("File.SaveAll")
+ Write-Output "saved"
+
+ if ($Activate) {
+ $plc = $sys.LookupTreeItem("TIPC^$PlcProject")
+ $plc.BootProjectAutostart = $true
+ $plc.GenerateBootProject($true)
+ $sys.ActivateConfiguration()
+ $sys.StartRestartTwinCAT()
+ Write-Output "activated and restarted TwinCAT"
+ }
+}
+finally {
+ if ($dte) { $dte.Quit() }
+ [MessageFilter]::Revoke()
+}
diff --git a/pyproject.toml b/pyproject.toml
index 8fc5c00..7d512d9 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -22,11 +22,22 @@ dependencies = [
[project.scripts]
lris2 = "lris2.cli:main"
+lris2-csu-demo = "lris2.csu_demo.__main__:main"
[project.optional-dependencies]
dev = [
"pytest",
]
+# The CSU daemon, on the host that reaches the CSU PLC: install.sh --extra csu
+csu = [
+ "cooethercat[twincat]@git+https://github.com/CaltechOpticalObservatories/coo-ethercat.git@twincat-backend",
+]
+# The CSU browser demo, on the host with the webcam and PLC: install.sh --extra csu-demo
+csu-demo = [
+ "cooethercat[twincat]@git+https://github.com/CaltechOpticalObservatories/coo-ethercat.git@twincat-backend",
+ "flask",
+ "waitress",
+]
# The camera daemon only, on the host that runs it: install.sh --extra camera.
# The camera_interface module it drives is built from lris2-camerad-instrument
camera = [
@@ -38,10 +49,11 @@ camera = [
lris2 = "src"
[tool.setuptools]
-packages = ["lris2", "lris2.cli", "lris2.driver"]
+packages = ["lris2", "lris2.cli", "lris2.csu", "lris2.csu_demo", "lris2.driver"]
[tool.setuptools.package-data]
"lris2.cli" = ["instrument.toml"]
+"lris2.csu_demo" = ["templates/*.html", "static/*"]
# The vendor drivers are vendored as submodules so they can be fixed in place,
# but their own dependencies still have to reach the environment.
diff --git a/src/csu/__init__.py b/src/csu/__init__.py
new file mode 100644
index 0000000..f3370d1
--- /dev/null
+++ b/src/csu/__init__.py
@@ -0,0 +1 @@
+"""LRIS2 CSU: libby keywords over the coo-ethercat axis API."""
diff --git a/src/csu/keywords.py b/src/csu/keywords.py
new file mode 100644
index 0000000..73b64a6
--- /dev/null
+++ b/src/csu/keywords.py
@@ -0,0 +1,184 @@
+"""libby keywords for the CSU bars: commands, motion state and drive telemetry."""
+
+from __future__ import annotations
+
+import json
+import threading
+from collections.abc import Callable
+from dataclasses import dataclass
+from typing import Any, Final, Protocol
+
+from cooethercat import Axis, AxisError, AxisSet, CoeType
+
+# Errors a keyword turns into a libby error reply instead of crashing the daemon
+TransportErrors = tuple[type[Exception], ...]
+
+
+class Registry(Protocol):
+ """The slice of libby's KeywordRegistry used here."""
+
+ def bool(self, name: str, **options: Any) -> Any:
+ """Register a bool keyword."""
+
+ def int(self, name: str, **options: Any) -> Any:
+ """Register an int keyword."""
+
+ def float(self, name: str, **options: Any) -> Any:
+ """Register a float keyword."""
+
+ def string(self, name: str, **options: Any) -> Any:
+ """Register a string keyword."""
+
+ def trigger(self, name: str, **options: Any) -> Any:
+ """Register a trigger keyword."""
+
+
+@dataclass(frozen=True)
+class Telemetry:
+ """One EPOS4 object served as a read-only keyword."""
+
+ keyword: str
+ index: int
+ subindex: int
+ kind: CoeType
+ scale: float
+ units: str
+ description: str
+
+
+# EPOS4 objects; the motors have no temperature sensor, so motor I2t stands in for winding heat
+TELEMETRY: Final = (
+ Telemetry("boardtemp", 0x3201, 1, CoeType.INT16, 0.1, "C", "Drive power stage temperature"),
+ Telemetry("i2tmotor", 0x3200, 1, CoeType.UINT16, 1.0, "%",
+ "Drive thermal model of the motor winding"),
+ Telemetry("i2tstage", 0x3200, 2, CoeType.UINT16, 1.0, "%",
+ "Drive thermal model of the power stage"),
+ Telemetry("current", 0x30D1, 1, CoeType.INT32, 1.0, "mA", "Motor current, averaged"),
+ Telemetry("supply", 0x2200, 1, CoeType.UINT16, 0.1, "V", "Drive supply voltage"),
+)
+
+
+# The readings the browser demo charts per bar
+_CHARTED: Final = tuple(item for item in TELEMETRY if item.keyword in ("boardtemp", "current"))
+
+
+def bar_number(axis: Axis) -> int:
+ """Return N for a bar named CSU-N, the suffix of its keywords."""
+ return int(axis.name.rsplit("-", 1)[1])
+
+
+class CsuKeywords:
+ """Translate keyword reads and writes into axis commands and drive reads."""
+
+ def __init__(self, axes: AxisSet, transport_errors: TransportErrors = (OSError,)) -> None:
+ self._axes = axes
+ self._errors = (AxisError, *transport_errors)
+ self._locks = {axis.name: threading.Lock() for axis in axes}
+
+ def register(self, registry: Registry) -> None:
+ """Register every bar's keywords plus the CSU-wide ones."""
+ for axis in self._axes:
+ self._register_bar(registry, axis)
+ registry.bool("ismoving", getter=self._guard(self.any_moving),
+ description="Any bar is moving")
+ registry.trigger("halt", action=self._guard(self.halt_all),
+ description="Stop every bar, continuing past failures")
+ registry.string("status", getter=self._guard(self.status_json),
+ description="Every bar's readbacks as JSON, keyed by bar name")
+ registry.string("telemetry", getter=self._guard(self.telemetry_json),
+ description="Every bar's board temperature (C) and current (mA) as JSON")
+
+ def _register_bar(self, registry: Registry, axis: Axis) -> None:
+ n, units = bar_number(axis), axis.config.units.name
+ registry.float(f"positionvalue{n}", units=units,
+ getter=self._guard(lambda: round(axis.position, 4)),
+ setter=self._guard(lambda target: self.move_to(axis, float(target))),
+ description=f"{axis.name} position; a write is an absolute move")
+ registry.float(f"velocity{n}", units=f"{units}/s",
+ getter=self._guard(lambda: float(axis.get("velocity"))),
+ setter=self._guard(lambda value: self.set_velocity(axis, float(value))),
+ description=f"{axis.name} profile velocity for moves")
+ registry.bool(f"ismoving{n}", getter=self._guard(lambda: axis.moving),
+ description=f"{axis.name} is moving")
+ registry.bool(f"isenabled{n}", getter=self._guard(lambda: axis.enabled),
+ setter=self._guard(lambda on: self.set_enabled(axis, bool(on))),
+ description=f"{axis.name} drive is energised; write to switch")
+ registry.int(f"error{n}", getter=self._guard(lambda: axis.error_id if axis.error else 0),
+ description=f"{axis.name} latched fault id, 0 when clear")
+ registry.trigger(f"halt{n}", action=self._guard(axis.stop),
+ description=f"Stop {axis.name}")
+ registry.trigger(f"reset{n}", action=self._guard(axis.reset),
+ description=f"Clear a latched fault on {axis.name}")
+ for item in TELEMETRY:
+ registry.float(f"{item.keyword}{n}", units=item.units,
+ getter=self._guard(lambda item=item: self.read_telemetry(axis, item)),
+ description=f"{axis.name}: {item.description}")
+
+ def move_to(self, axis: Axis, target: float) -> None:
+ """Start an absolute move, refusing while the bar is already moving."""
+ with self._locks[axis.name]:
+ if axis.moving:
+ raise AxisError(f"{axis.name} is already moving")
+ # A bar never given a velocity holds 0, which the PLC would fault on
+ velocity = float(axis.get("velocity")) or axis.config.limits.velocity
+ axis.move_absolute(target, velocity=velocity, wait=False)
+
+ def set_velocity(self, axis: Axis, value: float) -> None:
+ """Set the profile velocity used by later moves, within the bar's limit."""
+ limit = axis.config.limits.velocity
+ if not 0 < value <= limit:
+ raise AxisError(f"{axis.name} velocity must be in (0, {limit}]")
+ axis.set("velocity", value)
+
+ def set_enabled(self, axis: Axis, on: bool) -> None:
+ """Energise or de-energise a bar's drive and wait for it to follow."""
+ with self._locks[axis.name]:
+ if on:
+ axis.enable()
+ else:
+ axis.disable()
+
+ def read_telemetry(self, axis: Axis, item: Telemetry) -> float:
+ """Read one drive object and scale it to engineering units."""
+ return round(float(axis.read_object(item.index, item.subindex, item.kind)) * item.scale, 2)
+
+ def status_json(self) -> str:
+ """Return every bar's status snapshot as one JSON object."""
+ return json.dumps({axis.name: axis.status() for axis in self._axes})
+
+ def telemetry_json(self) -> str:
+ """Return every bar's board temperature and current, null where a drive fails to answer."""
+ readings: dict[str, dict[str, float | None]] = {}
+ for axis in self._axes:
+ values: dict[str, float | None] = {}
+ for item in _CHARTED:
+ try:
+ values[item.keyword] = self.read_telemetry(axis, item)
+ except self._errors:
+ values[item.keyword] = None
+ readings[axis.name] = values
+ return json.dumps(readings)
+
+ def any_moving(self) -> bool:
+ """Return whether any bar is moving."""
+ return any(axis.moving for axis in self._axes)
+
+ def halt_all(self) -> None:
+ """Stop every bar, raising afterwards if any of them could not be told to."""
+ failures = []
+ for axis in self._axes:
+ try:
+ axis.stop()
+ except self._errors as error:
+ failures.append(f"{axis.name}: {error}")
+ if failures:
+ raise RuntimeError("halt failed for " + "; ".join(failures))
+
+ def _guard(self, call: Callable[..., Any]) -> Callable[..., Any]:
+ """Report axis and transport failures as RuntimeError, which libby replies with."""
+ def guarded(*args: Any) -> Any:
+ try:
+ return call(*args)
+ except self._errors as error:
+ raise RuntimeError(str(error)) from error
+ return guarded
diff --git a/src/csu_demo/__init__.py b/src/csu_demo/__init__.py
new file mode 100644
index 0000000..2742a56
--- /dev/null
+++ b/src/csu_demo/__init__.py
@@ -0,0 +1 @@
+"""Browser demo of the CSU prototype: webcam plus axis controls over ADS."""
diff --git a/src/csu_demo/__main__.py b/src/csu_demo/__main__.py
new file mode 100644
index 0000000..b666f1c
--- /dev/null
+++ b/src/csu_demo/__main__.py
@@ -0,0 +1,143 @@
+"""Serve the CSU demo page: ``lris2-csu-demo --config config/csu/csu.yaml``."""
+
+from __future__ import annotations
+
+import argparse
+import dataclasses
+import os
+import shlex
+import signal
+import sys
+from pathlib import Path
+
+import waitress
+import yaml
+from cooethercat import Axis, AxisSet
+from cooethercat.backends.sim import open_simulated
+from cooethercat.config import Backend, TopologyConfig, parse_topology
+from libby import Client
+from libby.errors import LibbyError
+
+from lris2.daemon import broker_url
+
+from .camera import CommandSource, SharedCamera, StreamFormat, gstreamer_argv
+from .control import Controller
+from .history import POLL_S, Poller, TelemetryHistory, record_telemetry
+from .layout import Layout, load_layout
+from .libby_backend import LibbyBackend
+from .power import PowerPanel
+from .presets import PresetStore
+from .web import create_app
+
+# Each open MJPEG stream holds a worker thread for as long as it is watched
+_SERVER_THREADS = 16
+PASSWORD_ENV = "LRIS2_CSU_DEMO_PASSWORD"
+# A daemon that is down or refuses a request; the page reports it and keeps polling
+_ERRORS: tuple[type[Exception], ...] = (OSError, LibbyError)
+
+
+def main() -> None:
+ """Run the demo server until interrupted, then disable every axis."""
+ # systemd and kill stop with SIGTERM; route it through the cleanup below
+ signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
+ args = _parse_args()
+ topology = _topology(args)
+ layout = load_layout(args.layout) if args.layout else Layout(rows=12, slots={})
+ camera = None if args.no_camera else SharedCamera(lambda: CommandSource(_capture_argv(args)))
+ client = None if args.sim else Client.rabbitmq(self_id="csu-demo", rabbitmq_url=broker_url())
+ history = TelemetryHistory()
+ power = None if client is None or args.no_power else PowerPanel(client, args.pdu)
+ pollers = _pollers(client, args, history, power)
+ with _open_axes(topology, args, client) as axes:
+ controller = Controller(
+ axes, PresetStore(args.presets), transport_errors=_ERRORS,
+ password=os.environ.get(PASSWORD_ENV) or None,
+ )
+ controller.start()
+ for poller in pollers:
+ poller.start()
+ try:
+ app = create_app(controller, camera, layout, history=history, power=power,
+ power_errors=_ERRORS)
+ waitress.serve(app, host=args.host, port=args.port, threads=_SERVER_THREADS)
+ finally:
+ for poller in pollers:
+ poller.stop()
+ controller.stop()
+
+
+def _pollers(client: Client | None, args: argparse.Namespace, history: TelemetryHistory,
+ power: PowerPanel | None) -> list[Poller]:
+ if client is None:
+ return []
+ pollers = [Poller("telemetry", POLL_S,
+ record_telemetry(lambda: client.get(f"{args.peer}.telemetry"), history),
+ _ERRORS + (ValueError,))]
+ if power is not None:
+ def refresh_power() -> None:
+ try:
+ power.refresh()
+ except _ERRORS as error:
+ power.fail(error)
+ raise
+ pollers.append(Poller("power", POLL_S, refresh_power, _ERRORS))
+ return pollers
+
+
+def _capture_argv(args: argparse.Namespace) -> list[str]:
+ stream = StreamFormat(args.width, args.height, args.fps, args.quality)
+ argv = gstreamer_argv(args.camera, stream)
+ return argv if args.camera_host is None else ["ssh", args.camera_host, shlex.join(argv)]
+
+
+def _topology(args: argparse.Namespace) -> TopologyConfig:
+ # The daemon's own config, so limits and units match what it enforces
+ with args.config.open(encoding="utf-8") as handle:
+ topology = parse_topology(yaml.safe_load(handle)["topology"], source=str(args.config))
+ return dataclasses.replace(topology, backend=Backend.SIM) if args.sim else topology
+
+
+def _open_axes(topology: TopologyConfig, args: argparse.Namespace,
+ client: Client | None) -> AxisSet:
+ if client is None:
+ return open_simulated(topology)
+ backend = LibbyBackend(client, args.peer)
+ axes = AxisSet(backend,
+ {config.keyword_name: Axis(backend, config) for config in topology.axes})
+ backend.open()
+ return axes
+
+
+def _default_presets_path() -> Path:
+ # systemd's StateDirectory= sets STATE_DIRECTORY; outside it use the XDG state dir
+ state = os.environ.get("STATE_DIRECTORY") or Path.home() / ".local/state/lris2"
+ return Path(state) / "csu-presets.json"
+
+
+def _parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--config", type=Path, required=True,
+ help="CSU daemon config listing the bars, e.g. config/csu/csu.yaml")
+ parser.add_argument("--sim", action="store_true", help="simulate the axes, no daemon")
+ parser.add_argument("--peer", default="lris2.csu", help="CSU daemon to drive the bars through")
+ parser.add_argument("--pdu", default="l2power.pdu-ethercat", help="PDU daemon feeding the CSU")
+ parser.add_argument("--no-power", action="store_true", help="hide the PDU panel")
+ parser.add_argument("--camera", default="/dev/video0", help="V4L2 device")
+ parser.add_argument("--camera-host", help="capture on this SSH host instead of locally")
+ parser.add_argument("--width", type=int, default=StreamFormat.width)
+ parser.add_argument("--height", type=int, default=StreamFormat.height)
+ parser.add_argument("--fps", type=int, default=StreamFormat.fps)
+ parser.add_argument("--quality", type=int, default=StreamFormat.quality,
+ help="JPEG quality 1-100")
+ parser.add_argument("--no-camera", action="store_true")
+ parser.add_argument("--layout", type=Path,
+ help="bar slots on the CSU, e.g. config/csu/layout.yaml")
+ parser.add_argument("--presets", type=Path, default=_default_presets_path(),
+ help="JSON file holding the save points")
+ parser.add_argument("--host", default="127.0.0.1")
+ parser.add_argument("--port", type=int, default=8080)
+ return parser.parse_args()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/csu_demo/camera.py b/src/csu_demo/camera.py
new file mode 100644
index 0000000..b54c1a5
--- /dev/null
+++ b/src/csu_demo/camera.py
@@ -0,0 +1,159 @@
+"""Shared MJPEG capture that runs only while someone is watching."""
+
+from __future__ import annotations
+
+import io
+import subprocess
+import threading
+from collections.abc import Iterator, Sequence
+from dataclasses import dataclass
+from typing import Final, Protocol, cast
+
+_SOI: Final = b"\xff\xd8"
+_EOI: Final = b"\xff\xd9"
+_READ_CHUNK: Final = 65536
+_FRAME_TIMEOUT_S: Final = 5.0
+
+
+class FrameSource(Protocol):
+ """A process-like source of concatenated JPEG frames."""
+
+ def read(self, size: int) -> bytes:
+ """Return up to ``size`` bytes, or ``b""`` at end of stream."""
+
+ def close(self) -> None:
+ """Stop producing frames."""
+
+
+@dataclass(frozen=True)
+class StreamFormat:
+ """What viewers receive; the camera always captures 1280x720 MJPEG at 30 fps."""
+
+ width: int = 960
+ height: int = 540
+ fps: int = 15
+ quality: int = 60
+
+
+def gstreamer_argv(device: str, stream: StreamFormat) -> list[str]:
+ """Return a pipeline that re-encodes the camera's MJPEG to a lighter stream."""
+ return [
+ "gst-launch-1.0", "-q", "v4l2src", f"device={device}",
+ "!", "image/jpeg,width=1280,height=720,framerate=30/1",
+ "!", "jpegdec", "!", "videorate", "!", f"video/x-raw,framerate={stream.fps}/1",
+ "!", "videoscale", "!", f"video/x-raw,width={stream.width},height={stream.height}",
+ "!", "jpegenc", f"quality={stream.quality}", "!", "fdsink",
+ ]
+
+
+class CommandSource:
+ """JPEG frames from a capture command's stdout."""
+
+ def __init__(self, argv: Sequence[str]) -> None:
+ # Lives until close(), so a with block cannot own it
+ self._process = subprocess.Popen( # pylint: disable=consider-using-with
+ argv, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
+ self._stdout = cast(io.BufferedReader, self._process.stdout)
+
+ def read(self, size: int) -> bytes:
+ """Return up to ``size`` bytes, or b"" once the command exits."""
+ return self._stdout.read1(size)
+
+ def close(self) -> None:
+ """Stop the command, killing it if it does not exit."""
+ self._process.terminate()
+ try:
+ self._process.wait(timeout=2.0)
+ except subprocess.TimeoutExpired:
+ self._process.kill()
+
+
+class SourceFactory(Protocol): # pylint: disable=too-few-public-methods
+ """Callable that starts a new capture."""
+
+ def __call__(self) -> FrameSource:
+ """Start capturing."""
+
+
+class SharedCamera:
+ """Fan one capture out to any number of viewers."""
+
+ def __init__(self, start_source: SourceFactory) -> None:
+ self._start_source = start_source
+ self._condition = threading.Condition()
+ self._frame: bytes | None = None
+ self._frame_number = 0
+ self._viewers = 0
+ self._source: FrameSource | None = None
+
+ @property
+ def viewers(self) -> int:
+ """Return how many streams are open."""
+ with self._condition:
+ return self._viewers
+
+ @property
+ def running(self) -> bool:
+ """Return whether a capture is active."""
+ with self._condition:
+ return self._source is not None
+
+ def frames(self) -> Iterator[bytes]:
+ """Yield JPEG frames for one viewer until the caller stops iterating."""
+ self._attach()
+ try:
+ seen = 0
+ while (frame := self._next_frame(seen)) is not None:
+ seen = frame[0]
+ yield frame[1]
+ finally:
+ self._detach()
+
+ def _next_frame(self, seen: int) -> tuple[int, bytes] | None:
+ """Wait for a frame newer than ``seen``; None once capture has ended."""
+ with self._condition:
+ fresh = self._condition.wait_for(
+ lambda: (self._frame is not None and self._frame_number != seen)
+ or self._source is None,
+ timeout=_FRAME_TIMEOUT_S,
+ )
+ if not fresh or self._frame is None:
+ return None
+ return self._frame_number, self._frame
+
+ def _attach(self) -> None:
+ with self._condition:
+ self._viewers += 1
+ if self._source is not None:
+ return
+ self._source = self._start_source()
+ source = self._source
+ threading.Thread(target=self._pump, args=(source,), name="camera", daemon=True).start()
+
+ def _detach(self) -> None:
+ with self._condition:
+ self._viewers -= 1
+ if self._viewers > 0 or self._source is None:
+ return
+ source, self._source = self._source, None
+ self._frame = None
+ self._condition.notify_all()
+ source.close()
+
+ def _pump(self, source: FrameSource) -> None:
+ buffer = b""
+ while chunk := source.read(_READ_CHUNK):
+ buffer += chunk
+ while (start := buffer.find(_SOI)) >= 0 and (end := buffer.find(_EOI, start + 2)) >= 0:
+ self._publish(buffer[start : end + 2])
+ buffer = buffer[end + 2 :]
+ with self._condition:
+ if self._source is source:
+ self._source = None
+ self._condition.notify_all()
+
+ def _publish(self, frame: bytes) -> None:
+ with self._condition:
+ self._frame = frame
+ self._frame_number += 1
+ self._condition.notify_all()
diff --git a/src/csu_demo/control.py b/src/csu_demo/control.py
new file mode 100644
index 0000000..96bf19c
--- /dev/null
+++ b/src/csu_demo/control.py
@@ -0,0 +1,260 @@
+"""Axis status cache and single-operator control over a coo-ethercat AxisSet."""
+
+from __future__ import annotations
+
+import secrets
+import threading
+import time
+from collections.abc import Callable, Mapping
+from dataclasses import dataclass
+from typing import Any, Final
+
+from cooethercat import Axis, AxisError, AxisSet
+
+from .presets import PresetError, PresetStore, SavedBar
+
+_POLL_PERIOD_S: Final = 0.25
+LEASE_S: Final = 15.0
+
+
+class ControlError(RuntimeError):
+ """Raised when a command is refused before it reaches an axis."""
+
+
+@dataclass
+class _Lease:
+ """Who may command axes, and until when."""
+
+ token: str
+ holder: str
+ expires: float
+
+
+class Controller: # pylint: disable=too-many-instance-attributes
+ """Serve cached axis status to many viewers and commands to one operator."""
+
+ def __init__(
+ self,
+ axes: AxisSet,
+ presets: PresetStore,
+ transport_errors: tuple[type[Exception], ...] = (OSError,),
+ clock: Callable[[], float] = time.monotonic,
+ password: str | None = None,
+ ) -> None:
+ self._axes = axes
+ self._password = password
+ self._presets = presets
+ self._transport_errors = (AxisError, *transport_errors)
+ self._clock = clock
+ self._lock = threading.Lock()
+ self._lease: _Lease | None = None
+ self._snapshot: dict[str, dict[str, Any]] = {}
+ self._poll_error: str | None = None
+ self._plc_state: str | None = None
+ self._shutdown = threading.Event()
+ self._poller: threading.Thread | None = None
+
+ def start(self) -> None:
+ """Begin refreshing the status cache in the background."""
+ self.refresh()
+ self._poller = threading.Thread(target=self._poll, name="axis status", daemon=True)
+ self._poller.start()
+
+ def stop(self) -> None:
+ """Stop polling and de-energise every axis, over a fresh link in case the old one died."""
+ self._shutdown.set()
+ if self._poller is not None:
+ self._poller.join(timeout=2.0)
+ self._reconnect()
+ failures = []
+ for axis in self._axes:
+ try:
+ axis.set("enable", False)
+ except self._transport_errors as error:
+ failures.append(f"{axis.name}: {error}")
+ if failures:
+ raise ControlError("could not disable " + "; ".join(failures))
+
+ def refresh(self) -> None:
+ """Read every axis once into the cache."""
+ try:
+ snapshot = {axis.name: axis.status() for axis in self._axes}
+ plc_state = str(self._axes.backend.controller_state())
+ except self._transport_errors as error:
+ with self._lock:
+ self._poll_error = str(error)
+ self._reconnect()
+ return
+ with self._lock:
+ self._snapshot, self._poll_error, self._plc_state = snapshot, None, plc_state
+
+ def _reconnect(self) -> None:
+ """Reopen the transport, so a dropped ADS link heals on a later poll."""
+ try:
+ self._axes.backend.close()
+ self._axes.backend.open()
+ except self._transport_errors as error:
+ with self._lock:
+ self._poll_error = f"reconnect failed: {error}"
+
+ def status(self, token: str | None) -> dict[str, Any]:
+ """Return the cached axes plus who holds control."""
+ with self._lock:
+ lease = self._live_lease()
+ return {
+ "axes": [
+ {"name": axis.name, "units": axis.config.units.name,
+ "max_velocity": axis.config.limits.velocity,
+ **self._snapshot.get(axis.name, {})}
+ for axis in self._axes
+ ],
+ "presets": self._presets.names(),
+ "error": self._poll_error,
+ "plc": self._plc_state,
+ "controller": lease.holder if lease else None,
+ "in_control": lease is not None and token == lease.token,
+ }
+
+ def acquire(self, holder: str, token: str | None, password: str | None = None) -> str:
+ """Take or renew control, returning the token the holder must present.
+
+ Taking control needs the password when one is set; renewing needs only the token.
+ """
+ with self._lock:
+ lease = self._live_lease()
+ if lease is not None and token != lease.token:
+ raise ControlError(f"{lease.holder} is in control")
+ if lease is not None:
+ lease.expires = self._clock() + LEASE_S
+ return lease.token
+ if self._password is not None and not secrets.compare_digest(
+ (password or "").encode(), self._password.encode()):
+ raise ControlError("wrong password")
+ self._lease = _Lease(secrets.token_urlsafe(16), holder, self._clock() + LEASE_S)
+ return self._lease.token
+
+ def release(self, token: str | None) -> None:
+ """Give up control if ``token`` holds it."""
+ with self._lock:
+ if self._lease is not None and self._lease.token == token:
+ self._lease = None
+
+ def command(self, token: str | None, axis_name: str, action: str, **params: float) -> None:
+ """Run one operator action on one axis."""
+ self._require_control(token)
+ axis = self._axes.axis(axis_name)
+ try:
+ self._run(axis, action, params)
+ except self._transport_errors as error:
+ raise ControlError(f"{axis_name} {action}: {error}") from error
+
+ @staticmethod
+ def _run(axis: Axis, action: str, params: dict[str, float]) -> None:
+ match action:
+ case "enable":
+ axis.enable()
+ case "disable":
+ axis.disable()
+ case "move_relative":
+ axis.move_relative(params["distance"], velocity=params["velocity"], wait=False)
+ case "move_absolute":
+ axis.move_absolute(params["target"], velocity=params["velocity"], wait=False)
+ case "reset":
+ axis.reset()
+ case "home":
+ axis.home()
+ case "stop":
+ axis.stop()
+ case _:
+ raise ControlError(f"unknown action {action!r}")
+
+ def save_preset(self, token: str | None, name: str) -> None:
+ """Store every bar's current position under ``name``."""
+ self._require_control(token)
+ try:
+ bars = {axis.name: SavedBar(axis.position, axis.enabled) for axis in self._axes}
+ self._presets.save(name, bars)
+ except (PresetError, *self._transport_errors) as error:
+ raise ControlError(f"save {name!r}: {error}") from error
+
+ def recall_preset(self, token: str | None, name: str) -> list[str]:
+ """Move every enabled bar to its saved target; return the bars left where they are."""
+ self._require_control(token)
+ try:
+ targets = self._presets.get(name)
+ moves = self._plan_recall(targets)
+ for axis, target in moves:
+ axis.move_absolute(target, velocity=axis.config.limits.velocity, wait=False)
+ except (PresetError, *self._transport_errors) as error:
+ raise ControlError(f"recall {name!r}: {error}") from error
+ moving = {axis.name for axis, _ in moves}
+ return [axis.name for axis in self._axes if axis.name not in moving]
+
+ def preset(self, name: str) -> dict[str, dict[str, Any]]:
+ """Return one save point by bar name, for display."""
+ try:
+ saved = self._presets.get(name)
+ except PresetError as error:
+ raise ControlError(str(error)) from error
+ return {bar_name: {"position": entry.position, "enabled": entry.enabled}
+ for bar_name, entry in saved.items()}
+
+ def delete_preset(self, token: str | None, name: str) -> None:
+ """Forget a save point."""
+ self._require_control(token)
+ try:
+ self._presets.delete(name)
+ except PresetError as error:
+ raise ControlError(str(error)) from error
+
+ def _plan_recall(self, saved: Mapping[str, SavedBar]) -> list[tuple[Axis, float]]:
+ """Pick the bars to move, refusing the whole recall if any target is out of travel."""
+ moves = []
+ for axis in self._axes:
+ if axis.name not in saved or not axis.enabled:
+ continue
+ target = saved[axis.name].position
+ limits = axis.config.limits
+ if not limits.position_is_allowed(target):
+ raise ControlError(
+ f"{axis.name} target {target} is outside travel "
+ f"[{limits.min_position}, {limits.max_position}]"
+ )
+ moves.append((axis, target))
+ return moves
+
+ def stop_all(self) -> None:
+ """Stop every axis, continuing past failures; open to every viewer on purpose."""
+ failures = []
+ for axis in self._axes:
+ try:
+ axis.stop()
+ except self._transport_errors as error:
+ failures.append(f"{axis.name}: {error}")
+ if failures:
+ raise ControlError("stop failed for " + "; ".join(failures))
+
+ def any_enabled(self) -> bool:
+ """Return whether the last poll saw any bar enabled."""
+ with self._lock:
+ return any(state.get("enabled") for state in self._snapshot.values())
+
+ def require_control(self, token: str | None) -> None:
+ """Refuse unless ``token`` holds control, renewing the lease when it does."""
+ self._require_control(token)
+
+ def _require_control(self, token: str | None) -> None:
+ with self._lock:
+ lease = self._live_lease()
+ if lease is None or token != lease.token:
+ raise ControlError("take control first")
+ lease.expires = self._clock() + LEASE_S
+
+ def _live_lease(self) -> _Lease | None:
+ if self._lease is not None and self._lease.expires < self._clock():
+ self._lease = None
+ return self._lease
+
+ def _poll(self) -> None:
+ while not self._shutdown.wait(_POLL_PERIOD_S):
+ self.refresh()
diff --git a/src/csu_demo/history.py b/src/csu_demo/history.py
new file mode 100644
index 0000000..044bd9b
--- /dev/null
+++ b/src/csu_demo/history.py
@@ -0,0 +1,86 @@
+"""Drive telemetry history kept in memory for the per-bar charts, and a periodic poller."""
+
+from __future__ import annotations
+
+import json
+import logging
+import threading
+import time
+from collections import deque
+from collections.abc import Callable
+from typing import Any, Final
+
+HISTORY_S: Final = 2 * 3600.0
+POLL_S: Final = 10.0
+
+_log = logging.getLogger(__name__)
+
+
+class TelemetryHistory:
+ """Timestamped readings per bar, trimmed to a fixed window."""
+
+ def __init__(self, window_s: float = HISTORY_S) -> None:
+ self._window_s = window_s
+ self._lock = threading.Lock()
+ self._samples: dict[str, deque[tuple[float, dict[str, float | None]]]] = {}
+
+ def add(self, when: float, readings: dict[str, dict[str, float | None]]) -> None:
+ """Record one reading of every bar taken at ``when`` (epoch seconds)."""
+ with self._lock:
+ for bar_name, values in readings.items():
+ samples = self._samples.setdefault(bar_name, deque())
+ samples.append((when, values))
+ while samples and samples[0][0] < when - self._window_s:
+ samples.popleft()
+
+ def all_series(self) -> dict[str, dict[str, list[Any]]]:
+ """Return every bar's history, keyed by bar name."""
+ with self._lock:
+ names = list(self._samples)
+ return {bar_name: self.series(bar_name) for bar_name in names}
+
+ def series(self, bar_name: str) -> dict[str, list[Any]]:
+ """Return one bar's history as parallel lists: time, then one list per reading."""
+ with self._lock:
+ samples = list(self._samples.get(bar_name, ()))
+ keys = sorted({key for _, values in samples for key in values})
+ return {"time": [when for when, _ in samples],
+ **{key: [values.get(key) for _, values in samples] for key in keys}}
+
+
+class Poller:
+ """Call a function every period on a daemon thread, logging the errors it is told to expect."""
+
+ def __init__(self, name: str, period_s: float, call: Callable[[], None],
+ errors: tuple[type[Exception], ...]) -> None:
+ self._call = call
+ self._errors = errors
+ self._period_s = period_s
+ self._stop = threading.Event()
+ self._thread = threading.Thread(target=self._run, name=name, daemon=True)
+
+ def start(self) -> None:
+ """Begin polling."""
+ self._thread.start()
+
+ def stop(self) -> None:
+ """Stop polling and wait for the thread."""
+ self._stop.set()
+ self._thread.join(timeout=2.0)
+
+ def _run(self) -> None:
+ while True:
+ try:
+ self._call()
+ except self._errors as error:
+ _log.warning("%s: %s", self._thread.name, error)
+ if self._stop.wait(self._period_s):
+ return
+
+
+def record_telemetry(read: Callable[[], str], history: TelemetryHistory,
+ clock: Callable[[], float] = time.time) -> Callable[[], None]:
+ """Return a poll step that reads the daemon's telemetry JSON into ``history``."""
+ def step() -> None:
+ history.add(clock(), json.loads(read()))
+ return step
diff --git a/src/csu_demo/layout.py b/src/csu_demo/layout.py
new file mode 100644
index 0000000..7a47d3f
--- /dev/null
+++ b/src/csu_demo/layout.py
@@ -0,0 +1,77 @@
+"""Where each CSU bar sits physically, as seen from the webcam."""
+
+from __future__ import annotations
+
+import enum
+from collections.abc import Mapping
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+import yaml
+
+
+class LayoutError(ValueError):
+ """Raised for a layout file that would mislabel a bar."""
+
+
+class Side(enum.StrEnum):
+ """Side of the slit a bar enters from, on screen."""
+
+ LEFT = "left"
+ RIGHT = "right"
+
+
+@dataclass(frozen=True)
+class Slot:
+ """One bar's physical slot and the on-screen direction of a positive move."""
+
+ side: Side
+ row: int
+ plus: Side
+
+
+@dataclass(frozen=True)
+class Layout:
+ """Rows of the CSU and the slot of every bar in service."""
+
+ rows: int
+ slots: Mapping[str, Slot]
+
+ def slot(self, bar_name: str) -> Slot | None:
+ """Return a bar's slot, or None when the bar is not placed."""
+ return self.slots.get(bar_name)
+
+
+def load_layout(path: Path) -> Layout:
+ """Read and validate a layout file."""
+ data = yaml.safe_load(path.read_text()) or {}
+ _reject_unknown(data, {"rows", "bars"}, str(path))
+ rows = int(data.get("rows", 12))
+ slots = {str(bar_name): _slot(entry, rows, f"{path}: {bar_name}")
+ for bar_name, entry in (data.get("bars") or {}).items()}
+ taken: dict[tuple[Side, int], str] = {}
+ for bar_name, slot in slots.items():
+ other = taken.setdefault((slot.side, slot.row), bar_name)
+ if other != bar_name:
+ raise LayoutError(f"{path}: {bar_name} and {other} both sit {slot.side} row {slot.row}")
+ return Layout(rows, slots)
+
+
+def _slot(entry: Any, rows: int, where: str) -> Slot:
+ if not isinstance(entry, Mapping):
+ raise LayoutError(f"{where}: expected side, row and plus")
+ _reject_unknown(entry, {"side", "row", "plus"}, where)
+ try:
+ slot = Slot(Side(entry["side"]), int(entry["row"]), Side(entry["plus"]))
+ except (KeyError, ValueError) as error:
+ raise LayoutError(f"{where}: {error}") from None
+ if not 1 <= slot.row <= rows:
+ raise LayoutError(f"{where}: row {slot.row} is outside 1..{rows}")
+ return slot
+
+
+def _reject_unknown(data: Mapping[str, Any], allowed: set[str], where: str) -> None:
+ unknown = set(data) - allowed
+ if unknown:
+ raise LayoutError(f"{where}: unknown keys {sorted(unknown)}")
diff --git a/src/csu_demo/libby_backend.py b/src/csu_demo/libby_backend.py
new file mode 100644
index 0000000..3fced8c
--- /dev/null
+++ b/src/csu_demo/libby_backend.py
@@ -0,0 +1,129 @@
+"""coo-ethercat axis backend that drives the bars through the ``lris2.csu`` daemon."""
+
+from __future__ import annotations
+
+import json
+import threading
+import time
+from collections.abc import Callable, Sequence
+from typing import Any, Final, Protocol
+
+from cooethercat import AxisError, CoeType, ControllerState, MoveMode
+from cooethercat.config import AxisConfig
+
+# One status read serves every bar's poll within this window
+_STATUS_TTL_S: Final = 0.1
+
+
+class KeywordClient(Protocol):
+ """The slice of ``libby.Client`` this backend uses."""
+
+ def get(self, name: str, *, timeout_s: float = ...) -> Any:
+ """Read a keyword's value."""
+
+ def set(self, name: str, value: Any, *, timeout_s: float | None = None) -> Any:
+ """Write a keyword."""
+
+
+def bar_number(axis: AxisConfig) -> int:
+ """Return N for a bar named CSU-N, the suffix of its daemon keywords."""
+ return int(axis.name.rsplit("-", 1)[1])
+
+
+class LibbyBackend:
+ """Axis backend speaking to the CSU daemon's keywords instead of the PLC."""
+
+ def __init__(self, client: KeywordClient, peer: str = "lris2.csu",
+ clock: Callable[[], float] = time.monotonic) -> None:
+ self._client = client
+ self._peer = peer
+ self._clock = clock
+ self._lock = threading.Lock()
+ self._status: dict[str, dict[str, Any]] = {}
+ self._status_time = float("-inf")
+ # The daemon takes absolute targets, so a move is assembled here before it is sent
+ self._pending: dict[str, dict[str, Any]] = {}
+
+ def open(self) -> None:
+ """Drop the cached status so the next read is fresh."""
+ self._invalidate()
+
+ def close(self) -> None:
+ """Drop the cached status; the client stays with its owner."""
+ self._invalidate()
+
+ def read_field(self, axis: AxisConfig, field: str) -> Any:
+ """Return one field, from the shared status read where it can."""
+ if field == "velocity":
+ return self._get(f"velocity{bar_number(axis)}")
+ try:
+ return self._bar_status(axis)[field]
+ except KeyError:
+ raise AxisError(f"{axis.name}: the CSU daemon does not report {field!r}") from None
+
+ def read_fields(self, axis: AxisConfig, fields: Sequence[str]) -> dict[str, Any]:
+ """Return several fields of one bar from one status read."""
+ status = self._bar_status(axis)
+ return {field: status[field] for field in fields}
+
+ def write_field(self, axis: AxisConfig, field: str, value: Any) -> None:
+ """Map a setting onto the daemon keyword that holds it."""
+ n = bar_number(axis)
+ match field:
+ case "enable":
+ self._set(f"isenabled{n}", bool(value))
+ case "velocity":
+ self._set(f"velocity{n}", float(value))
+ case "mode" | "target":
+ self._pending.setdefault(axis.name, {})[field] = value
+ case _:
+ raise AxisError(f"{axis.name}: {field!r} cannot be set through the CSU daemon")
+
+ def fire_trigger(self, axis: AxisConfig, field: str) -> None:
+ """Map an action onto the daemon keyword that performs it."""
+ n = bar_number(axis)
+ match field:
+ case "move":
+ self._set(f"positionvalue{n}", self._target(axis))
+ case "stop":
+ self._set(f"halt{n}", True)
+ case "reset":
+ self._set(f"reset{n}", True)
+ case _:
+ raise AxisError(f"{axis.name}: {field!r} is not available through the CSU daemon")
+
+ def read_object(self, axis: AxisConfig, index: int, subindex: int, kind: CoeType) -> int:
+ """Refuse: CoE objects are served as telemetry keywords instead."""
+ raise AxisError(f"{axis.name}: CoE objects are served as telemetry keywords, not here")
+
+ def controller_state(self) -> ControllerState:
+ """Return the PLC runtime mode the daemon reports."""
+ return ControllerState(self._get("plcstate"))
+
+ def _target(self, axis: AxisConfig) -> float:
+ pending = self._pending.pop(axis.name, {})
+ if "target" not in pending:
+ raise AxisError(f"{axis.name}: move fired without a target")
+ target = float(pending["target"])
+ if pending.get("mode") == MoveMode.RELATIVE:
+ self._invalidate()
+ target += float(self._bar_status(axis)["position"])
+ return target
+
+ def _bar_status(self, axis: AxisConfig) -> dict[str, Any]:
+ with self._lock:
+ if self._clock() - self._status_time > _STATUS_TTL_S:
+ self._status = json.loads(self._get("status"))
+ self._status_time = self._clock()
+ return self._status[axis.name]
+
+ def _invalidate(self) -> None:
+ with self._lock:
+ self._status_time = float("-inf")
+
+ def _get(self, keyword: str) -> Any:
+ return self._client.get(f"{self._peer}.{keyword}")
+
+ def _set(self, keyword: str, value: Any) -> None:
+ self._client.set(f"{self._peer}.{keyword}", value)
+ self._invalidate()
diff --git a/src/csu_demo/power.py b/src/csu_demo/power.py
new file mode 100644
index 0000000..9e32bec
--- /dev/null
+++ b/src/csu_demo/power.py
@@ -0,0 +1,66 @@
+"""CSU lab PDU outlets as the demo shows and switches them, through the l2power daemon."""
+
+from __future__ import annotations
+
+import threading
+from typing import Any, Final
+
+from .libby_backend import KeywordClient
+
+# Outlet keyword name, label; only the drives may be switched from the page
+OUTLETS: Final = (
+ ("ethercat", "EtherCAT drives"),
+ ("plc", "PLC"),
+ ("gateway", "lris2-ethercat"),
+ ("windows", "Windows XAE PC"),
+ ("lantronix", "Lantronix"),
+)
+SWITCHABLE: Final = frozenset({"ethercat"})
+
+
+class PowerError(RuntimeError):
+ """Raised when a power switch is refused."""
+
+
+class PowerPanel:
+ """Cache outlet readings and switch the drives outlet."""
+
+ def __init__(self, client: KeywordClient, peer: str = "l2power.pdu-ethercat") -> None:
+ self._client = client
+ self._peer = peer
+ self._lock = threading.Lock()
+ self._outlets: list[dict[str, Any]] = []
+ self._error: str | None = None
+
+ def refresh(self) -> None:
+ """Read every outlet's state, power and current."""
+ outlets = []
+ for name, label in OUTLETS:
+ outlets.append({
+ "name": name, "label": label, "switchable": name in SWITCHABLE,
+ "on": bool(self._get(f"state_{name}")),
+ "power": float(self._get(f"power_{name}")),
+ "current": float(self._get(f"current_{name}")),
+ })
+ with self._lock:
+ self._outlets, self._error = outlets, None
+
+ def fail(self, error: Exception) -> None:
+ """Remember why the last refresh failed, for the page."""
+ with self._lock:
+ self._error = str(error)
+
+ def status(self) -> dict[str, Any]:
+ """Return the cached outlets and the last refresh error."""
+ with self._lock:
+ return {"outlets": list(self._outlets), "error": self._error}
+
+ def switch(self, outlet: str, on: bool) -> None:
+ """Switch one outlet the page may switch."""
+ if outlet not in SWITCHABLE:
+ raise PowerError(f"{outlet} cannot be switched from here")
+ self._client.set(f"{self._peer}.state_{outlet}", on)
+ self.refresh()
+
+ def _get(self, keyword: str) -> Any:
+ return self._client.get(f"{self._peer}.{keyword}")
diff --git a/src/csu_demo/presets.py b/src/csu_demo/presets.py
new file mode 100644
index 0000000..4872cb1
--- /dev/null
+++ b/src/csu_demo/presets.py
@@ -0,0 +1,87 @@
+"""Named save points, each holding every bar's position and enabled state, in a JSON file."""
+
+from __future__ import annotations
+
+import json
+import os
+import threading
+from collections.abc import Mapping
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from types import MappingProxyType
+from typing import Any, Final
+
+MAX_NAME_LENGTH: Final = 40
+
+
+class PresetError(ValueError):
+ """Raised for an unknown or invalid save point."""
+
+
+@dataclass(frozen=True)
+class SavedBar:
+ """One bar as it was when the save point was taken."""
+
+ position: float
+ enabled: bool | None = None
+
+
+class PresetStore:
+ """Save points shared by every viewer and persisted across restarts."""
+
+ def __init__(self, path: Path) -> None:
+ self._path = path
+ self._lock = threading.Lock()
+ self._presets: dict[str, dict[str, SavedBar]] = self._load()
+
+ def names(self) -> list[str]:
+ """Return save point names in the order they were created."""
+ with self._lock:
+ return list(self._presets)
+
+ def get(self, name: str) -> Mapping[str, SavedBar]:
+ """Return one save point by bar name."""
+ with self._lock:
+ try:
+ return MappingProxyType(dict(self._presets[name]))
+ except KeyError:
+ raise PresetError(f"no save point {name!r}") from None
+
+ def save(self, name: str, bars: Mapping[str, SavedBar]) -> None:
+ """Store or overwrite a save point."""
+ name = name.strip()
+ if not name or len(name) > MAX_NAME_LENGTH:
+ raise PresetError(f"save point names are 1 to {MAX_NAME_LENGTH} characters")
+ with self._lock:
+ self._presets[name] = dict(bars)
+ self._write()
+
+ def delete(self, name: str) -> None:
+ """Remove a save point."""
+ with self._lock:
+ if self._presets.pop(name, None) is None:
+ raise PresetError(f"no save point {name!r}")
+ self._write()
+
+ def _load(self) -> dict[str, dict[str, SavedBar]]:
+ if not self._path.exists():
+ return {}
+ raw = json.loads(self._path.read_text())
+ return {str(name): {str(bar_name): _saved_bar(entry) for bar_name, entry in bars.items()}
+ for name, bars in raw.items()}
+
+ def _write(self) -> None:
+ self._path.parent.mkdir(parents=True, exist_ok=True)
+ staging = self._path.with_suffix(".tmp")
+ payload = {name: {bar_name: asdict(saved) for bar_name, saved in bars.items()}
+ for name, bars in self._presets.items()}
+ staging.write_text(json.dumps(payload, indent=2))
+ os.replace(staging, self._path)
+
+
+def _saved_bar(entry: Any) -> SavedBar:
+ # Save points written before enabled states were recorded hold a bare position
+ if isinstance(entry, int | float):
+ return SavedBar(float(entry))
+ enabled = entry.get("enabled")
+ return SavedBar(float(entry["position"]), None if enabled is None else bool(enabled))
diff --git a/src/csu_demo/static/demo.css b/src/csu_demo/static/demo.css
new file mode 100644
index 0000000..8f0a3b2
--- /dev/null
+++ b/src/csu_demo/static/demo.css
@@ -0,0 +1,88 @@
+body { font-family: system-ui, sans-serif; margin: 0; background: #16181d; color: #e6e6e6; }
+header { display: flex; gap: 0.75rem; align-items: center; padding: 0.75rem 1rem; background: #20232a; }
+header h1 { font-size: 1.1rem; margin: 0 auto 0 0; }
+main { display: grid; grid-template-columns: minmax(320px, 2fr) minmax(0, 3fr); gap: 1rem; padding: 0 1rem 1rem; }
+#act { display: flex; flex-direction: column; gap: 0.75rem; min-width: 0; }
+#bars { min-width: 0; }
+#charts { grid-column: 1 / -1; }
+@media (max-width: 1100px) { main { grid-template-columns: 1fr; } }
+#camera img { width: 100%; border-radius: 4px; }
+.chip { border: 1px solid #3a3f4a; border-radius: 4px; padding: 0.15rem 0.5rem; white-space: nowrap; }
+.chip.ok { border-color: #3fb950; }
+.chip.bad { border-color: #f85149; background: #4a1e1e; }
+table { border-collapse: collapse; font-variant-numeric: tabular-nums; }
+th, td { padding: 0.3rem 0.5rem; border-bottom: 1px solid #2c3038; text-align: left; }
+td.num { text-align: right; }
+input { width: 4.5rem; background: #2a2e36; color: inherit; border: 1px solid #3a3f4a; padding: 0.2rem; }
+button { background: #2f6feb; color: white; border: 0; padding: 0.3rem 0.6rem; border-radius: 3px; cursor: pointer; }
+button:disabled { background: #3a3f4a; cursor: default; }
+button.danger { background: #d1242f; font-weight: bold; }
+.fault { color: #ff7b72; font-weight: bold; }
+.moving { color: #e3b341; }
+#message { padding: 0.5rem; margin: 0.5rem 1rem 0; border-radius: 3px; }
+#message.error { background: #5a1e1e; }
+#message.notice { background: #2a2e36; border-left: 3px solid #8b949e; }
+button.selected { background: #a5d6ff; color: #16181d; }
+#presets { display: flex; flex-wrap: wrap; gap: 0.4rem; align-items: center; margin-bottom: 0.75rem; }
+#presets .preset { display: inline-flex; gap: 2px; }
+#preset-name { width: 9rem; }
+button.small { padding: 0.3rem 0.4rem; background: #3a3f4a; }
+#csu { display: grid; grid-template-columns: 1fr 2.2rem 1fr; gap: 3px 0; background: #20232a;
+ padding: 6px; border-radius: 4px; }
+/* One frame per module of six bars; drawn behind the bars */
+.module { border: 1px solid #3a3f4a; border-radius: 4px; margin: -3px; z-index: 0; }
+.module-gap { height: 0.6rem; }
+.slot, .slit { z-index: 1; }
+.slot { display: flex; min-height: 2.1rem; }
+.slot.left { grid-column: 1; justify-content: flex-start; }
+.slot.right { grid-column: 3; justify-content: flex-end; }
+.slit { grid-column: 2; text-align: center; color: #6e7681; font-size: 0.75rem; align-self: center; }
+.bar { display: flex; gap: 0.4rem; align-items: center; width: 92%; min-width: 0; overflow: hidden; background: #3a3f4a;
+ border-radius: 0; padding: 0.25rem 0.5rem; color: #e6e6e6; text-align: left; }
+.slot.left .bar { border-right: 4px solid #8b949e; }
+.slot.right .bar { border-left: 4px solid #8b949e; flex-direction: row-reverse; text-align: right; }
+.bar .name { font-weight: bold; min-width: 3.6rem; }
+.bar .pos { font-variant-numeric: tabular-nums; min-width: 3.8rem; }
+.bar .state { color: #8b949e; font-size: 0.85rem; }
+.bar .saved { color: #a5d6ff; font-size: 0.8rem; }
+.bar .spark { display: inline-flex; align-items: center; gap: 0.25rem; font-size: 0.75rem;
+ color: #8b949e; font-variant-numeric: tabular-nums; }
+.bar .spark svg { width: 50px; height: 18px; flex: none; }
+.bar .spark polyline { fill: none; stroke-width: 1.2; vector-effect: non-scaling-stroke; }
+.bar .spark.temp polyline { stroke: #ff9830; }
+.bar .spark.cur polyline { stroke: #5794f2; }
+.bar .spark .value { min-width: 3rem; }
+.bar.live { background: #1f3b2a; }
+.slot.left .bar.live { border-right-color: #3fb950; }
+.slot.right .bar.live { border-left-color: #3fb950; }
+.bar.off { opacity: 0.45; }
+.bar.faulted { background: #4a1e1e; }
+.bar.moving .state { color: #e3b341; }
+.bar.chosen { outline: 2px solid #a5d6ff; outline-offset: 1px; }
+#unplaced { margin-top: 0.6rem; display: flex; flex-wrap: wrap; gap: 4px; align-items: center; }
+#unplaced .bar { width: auto; }
+.slot { min-width: 0; }
+#panel { padding: 0.6rem; background: #20232a; border-radius: 4px; display: grid; gap: 0.4rem; }
+#panel-body { display: grid; gap: 0.4rem; }
+#panel-title { font-weight: bold; }
+#panel-status { color: #8b949e; }
+#panel-actions { display: flex; gap: 0.3rem; }
+#panel-actions button[data-action^="move"] { min-width: 3rem; font-size: 1rem; }
+#panel-body[hidden], #unplaced[hidden] { display: none; }
+#unplaced-list { display: flex; flex-wrap: wrap; gap: 4px; }
+
+#charts { display: flex; gap: 1em; flex-wrap: wrap; }
+.chart { margin: 0; flex: 1 1 420px; display: grid; grid-template-columns: 1fr 215px; gap: 0.4em;
+ background: #1b1d22; border-radius: 4px; padding: 0.4em; }
+.chart figcaption { grid-column: 1 / -1; font-weight: bold; }
+.chart svg { width: 100%; height: 200px; }
+.chart polyline { fill: none; stroke-width: 1.5; vector-effect: non-scaling-stroke; }
+.chart .grid { stroke: #333; stroke-width: 1; vector-effect: non-scaling-stroke; }
+.chart text { fill: #999; font-size: 11px; }
+.legend { font-size: 0.8em; border-collapse: collapse; align-self: start; max-height: 200px;
+ overflow-y: auto; display: block; }
+.legend th { color: #6cf; text-align: right; font-weight: normal; padding: 0 0.4em; }
+.legend td { text-align: right; padding: 0 0.4em; cursor: pointer; white-space: nowrap; }
+.legend td:first-child { text-align: left; }
+.legend tr.hidden td { opacity: 0.35; }
+.swatch { display: inline-block; width: 10px; height: 3px; margin-right: 4px; vertical-align: middle; }
diff --git a/src/csu_demo/static/demo.js b/src/csu_demo/static/demo.js
new file mode 100644
index 0000000..24efbb3
--- /dev/null
+++ b/src/csu_demo/static/demo.js
@@ -0,0 +1,455 @@
+// Draw the CSU as seen from the webcam, keep it live, and send operator commands
+const STATES = ["disabled", "standstill", "homing", "moving", "moving", "stopping", "error stop"];
+const messageBox = document.getElementById("message");
+const panel = document.getElementById("panel");
+let inControl = false;
+let layout = { rows: 12, bars: {} };
+let axesByName = {};
+let chosenBar = null;
+let selected = null; // { name, bars } of the save point shown beside the live values
+
+async function api(method, path, body) {
+ const response = await fetch(path, {
+ method,
+ headers: { "Content-Type": "application/json" },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || response.statusText);
+ return data;
+}
+
+function showMessage(text, kind = "error") {
+ messageBox.textContent = text || "";
+ messageBox.className = kind;
+ messageBox.hidden = !text;
+}
+
+const showError = (text) => showMessage(text, "error");
+const showNotice = (text) => showMessage(text, "notice");
+
+function barElement(name) {
+ const bar = document.createElement("button");
+ bar.className = "bar";
+ bar.dataset.bar = name;
+ bar.innerHTML = `${name}
+
+
+ `;
+ bar.addEventListener("click", () => chooseBar(name));
+ return bar;
+}
+
+// The CSU is built from modules of six bars; a spacer row separates upper and lower modules
+const MODULE_ROWS = 6;
+const gridRow = (row) => row + Math.floor((row - 1) / MODULE_ROWS);
+
+function buildCsu(axes) {
+ const csu = document.getElementById("csu");
+ const cells = [];
+ for (let first = 1; first <= layout.rows; first += MODULE_ROWS) {
+ const last = Math.min(first + MODULE_ROWS - 1, layout.rows);
+ for (const column of [1, 3]) {
+ const frame = document.createElement("div");
+ frame.className = "module";
+ frame.style.gridColumn = column;
+ frame.style.gridRow = `${gridRow(first)} / ${gridRow(last) + 1}`;
+ cells.push(frame);
+ }
+ if (last < layout.rows) {
+ const gap = document.createElement("div");
+ gap.className = "module-gap";
+ gap.style.gridRow = gridRow(last) + 1;
+ cells.push(gap);
+ }
+ }
+ for (let row = 1; row <= layout.rows; row += 1) {
+ for (const side of ["left", "right"]) {
+ const cell = document.createElement("div");
+ cell.className = `slot ${side}`;
+ cell.style.gridRow = gridRow(row);
+ cell.id = `slot-${side}-${row}`;
+ cells.push(cell);
+ }
+ const slit = document.createElement("div");
+ slit.className = "slit";
+ slit.style.gridRow = gridRow(row);
+ slit.textContent = row;
+ cells.push(slit);
+ }
+ csu.replaceChildren(...cells);
+
+ const unplaced = [];
+ for (const axis of axes) {
+ const slot = layout.bars[axis.name];
+ const bar = barElement(axis.name);
+ if (slot) {
+ document.getElementById(`slot-${slot.side}-${slot.row}`).append(bar);
+ } else {
+ unplaced.push(bar);
+ }
+ }
+ document.getElementById("unplaced-list").replaceChildren(...unplaced);
+ document.getElementById("unplaced").hidden = unplaced.length === 0;
+}
+
+function renderBar(axis) {
+ const bar = document.querySelector(`.bar[data-bar="${axis.name}"]`);
+ if (!bar) return;
+ bar.classList.toggle("live", axis.enabled && !axis.error);
+ bar.classList.toggle("off", !axis.enabled && !axis.error);
+ bar.classList.toggle("faulted", axis.error);
+ bar.classList.toggle("moving", axis.moving);
+ bar.classList.toggle("chosen", axis.name === chosenBar);
+ bar.querySelector(".pos").textContent = axis.position === undefined ? "–" : axis.position.toFixed(2);
+ bar.querySelector(".state").textContent = axis.error
+ ? `fault 0x${axis.error_id.toString(16)}` : (STATES[axis.state] ?? "–");
+ const saved = selected?.bars[axis.name];
+ const was = { true: "on", false: "off", null: "?" }[saved?.enabled ?? null];
+ bar.querySelector(".saved").textContent = saved ? `saved ${saved.position.toFixed(2)} (${was})` : "";
+}
+
+function slotLabel(name) {
+ const slot = layout.bars[name];
+ return slot ? `${slot.side} side, row ${slot.row} from the top` : "not placed";
+}
+
+function renderPanel() {
+ const axis = axesByName[chosenBar];
+ document.getElementById("panel-body").hidden = !axis;
+ if (!axis) {
+ document.getElementById("panel-title").textContent = "Click a bar to control it";
+ return;
+ }
+ document.getElementById("panel-title").textContent = `${axis.name}: ${slotLabel(axis.name)}`;
+ document.getElementById("panel-status").textContent =
+ `${axis.position.toFixed(3)} ${axis.units}, ${STATES[axis.state] ?? "–"}, ` +
+ (axis.enabled ? "enabled" : "disabled") + (axis.error ? `, fault 0x${axis.error_id.toString(16)}` : "");
+ for (const units of panel.querySelectorAll(".units")) units.textContent = axis.units;
+ const velocity = document.getElementById("velocity");
+ velocity.max = axis.max_velocity;
+ if (!velocity.value) velocity.value = Math.min(5, axis.max_velocity);
+ for (const button of panel.querySelectorAll("button")) button.disabled = !inControl;
+}
+
+function chooseBar(name) {
+ chosenBar = chosenBar === name ? null : name;
+ document.getElementById("velocity").value = "";
+ poll();
+}
+
+// Grafana-style time charts: one line per bar, shared time axis, legend with last and max
+const PALETTE = ["#73bf69", "#f2cc0c", "#8ab8ff", "#ff780a", "#f2495c", "#5794f2", "#b877d9",
+ "#705da0", "#37872d", "#fade2a", "#3274d9", "#e0b400", "#c4162a", "#1f78c1",
+ "#ba43a9", "#9ac48a", "#ffb357", "#ff7383", "#a352cc", "#56a64b", "#ca95e5",
+ "#4ab0ff", "#ffee52"];
+const hiddenBars = new Set();
+
+function niceTicks(lo, hi, count) {
+ const step = 10 ** Math.floor(Math.log10((hi - lo) / count || 1));
+ const best = [1, 2, 5, 10].map((m) => m * step).find((s) => (hi - lo) / s <= count) || step * 10;
+ const ticks = [];
+ for (let v = Math.ceil(lo / best) * best; v <= hi + 1e-9; v += best) ticks.push(v);
+ return ticks;
+}
+
+// Current is signed by torque direction; the charts show its magnitude, which is what heats
+const magnitude = (key, v) => (key === "current" && v != null ? Math.abs(v) : v);
+
+function drawChart(figure, history) {
+ const key = figure.dataset.key;
+ const unit = figure.dataset.unit;
+ const names = Object.keys(history).sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
+ const series = names.map((name, index) => ({
+ name, color: PALETTE[index % PALETTE.length],
+ points: history[name].time.map((t, i) => [t, magnitude(key, (history[name][key] || [])[i])])
+ .filter(([, v]) => v != null),
+ }));
+ const visible = series.filter((s) => !hiddenBars.has(s.name) && s.points.length);
+ const svg = figure.querySelector("svg");
+ const all = visible.flatMap((s) => s.points);
+ if (all.length < 2) {
+ svg.innerHTML = 'collecting… one sample every 10 s';
+ } else {
+ const t0 = Math.min(...all.map(([t]) => t)), t1 = Math.max(...all.map(([t]) => t));
+ let lo = Math.min(...all.map(([, v]) => v)), hi = Math.max(...all.map(([, v]) => v));
+ if (hi - lo < 1e-6) { lo -= 1; hi += 1; }
+ const pad = (hi - lo) * 0.05; lo -= pad; hi += pad;
+ const x = (t) => 50 + ((t - t0) / Math.max(t1 - t0, 1)) * 545;
+ const y = (v) => 185 - ((v - lo) / (hi - lo)) * 175;
+ const grid = niceTicks(lo, hi, 5).map((v) =>
+ `` +
+ `${+v.toFixed(2)} ${unit}`).join("");
+ const times = [0, 0.5, 1].map((f) => t0 + f * (t1 - t0)).map((t) =>
+ `${new Date(t * 1000).toTimeString().slice(0, 5)}`).join("");
+ const lines = visible.map((s) =>
+ ``).join("");
+ svg.innerHTML = grid + times + lines;
+ }
+ const rows = series.map((s) => {
+ const values = s.points.map(([, v]) => v);
+ const last = values.length ? values[values.length - 1] : null;
+ const max = values.length ? Math.max(...values) : null;
+ const fmt = (v) => (v == null ? "–" : `${+v.toFixed(1)} ${unit}`);
+ return `
` +
+ `| ${s.name} | ` +
+ `${fmt(last)} | ${fmt(max)} |
`;
+ }).join("");
+ figure.querySelector(".legend").innerHTML = `| Name | Last | Max |
${rows}`;
+}
+
+let lastHistory = {};
+function redrawCharts() {
+ for (const figure of document.querySelectorAll(".chart")) drawChart(figure, lastHistory);
+ drawSparklines(lastHistory);
+}
+
+// Each sparkline scales to its own range, so it shows the trend; the number shows the value
+function sparkline(svg, values) {
+ const points = values.filter((v) => v != null);
+ if (points.length < 2) { svg.innerHTML = ""; return; }
+ let lo = Math.min(...points), hi = Math.max(...points);
+ if (hi - lo < 1e-6) { lo -= 1; hi += 1; }
+ const step = 70 / (points.length - 1);
+ const line = points.map((v, i) => `${(i * step).toFixed(1)},${(17 - ((v - lo) / (hi - lo)) * 16).toFixed(1)}`);
+ svg.innerHTML = ``;
+}
+
+function drawSparklines(history) {
+ for (const bar of document.querySelectorAll(".bar[data-bar]")) {
+ const series = history[bar.dataset.bar];
+ for (const [cls, key, unit] of [["temp", "boardtemp", "°C"], ["cur", "current", "mA"]]) {
+ const spark = bar.querySelector(`.spark.${cls}`);
+ const values = (series?.[key] || []).map((v) => magnitude(key, v));
+ const last = values.length ? values[values.length - 1] : null;
+ sparkline(spark.querySelector("svg"), values);
+ spark.querySelector(".value").textContent = last == null ? "" : `${last.toFixed(1)} ${unit}`;
+ }
+ }
+}
+
+async function drawCharts() {
+ try {
+ lastHistory = await api("GET", "/api/history");
+ redrawCharts();
+ } catch (error) {
+ showError(`history: ${error.message}`);
+ }
+}
+
+document.getElementById("charts").addEventListener("click", (event) => {
+ const row = event.target.closest("tr[data-bar]");
+ if (!row) return;
+ const name = row.dataset.bar;
+ if (hiddenBars.has(name)) hiddenBars.delete(name); else hiddenBars.add(name);
+ redrawCharts();
+});
+setInterval(drawCharts, 10000);
+drawCharts();
+
+let drivesOutlet = null;
+
+async function pollPower() {
+ const chip = document.getElementById("power-chip");
+ if (!chip) return;
+ try {
+ const status = await api("GET", "/api/power");
+ drivesOutlet = status.outlets.find((outlet) => outlet.switchable) || null;
+ const others = status.outlets.filter((outlet) => !outlet.switchable);
+ chip.title = others.map((o) => `${o.label}: ${o.on ? "on" : "off"}, ${o.power.toFixed(1)} W`).join("\n");
+ if (drivesOutlet) {
+ document.getElementById("power-text").textContent =
+ `Drives ${drivesOutlet.on ? "on" : "off"}, ${drivesOutlet.power.toFixed(1)} W`;
+ chip.className = `chip ${drivesOutlet.on ? "ok" : "bad"}`;
+ const button = document.getElementById("power-switch");
+ button.textContent = drivesOutlet.on ? "Power off" : "Power on";
+ button.disabled = !inControl;
+ }
+ if (status.error) showError(`PDU: ${status.error}`);
+ } catch (error) {
+ showError(`PDU: ${error.message}`);
+ }
+}
+
+document.getElementById("power-switch")?.addEventListener("click", () => {
+ if (drivesOutlet) switchPower(drivesOutlet);
+});
+
+async function switchPower(outlet) {
+ const on = !outlet.on;
+ if (!on && !confirm(`Switch ${outlet.label} off?`)) return;
+ try {
+ await api("POST", `/api/power/${outlet.name}`, { on });
+ pollPower();
+ } catch (error) {
+ showError(error.message);
+ }
+}
+setInterval(pollPower, 5000);
+pollPower();
+
+// The layout records which way a positive move takes each bar on screen
+function signedStep(name, towards) {
+ const step = Math.abs(parseFloat(document.getElementById("step").value));
+ const plus = layout.bars[name]?.plus ?? "right";
+ return towards === plus ? step : -step;
+}
+
+panel.querySelector("#panel-actions").addEventListener("click", async (event) => {
+ const action = event.target.dataset.action;
+ if (!action || !chosenBar) return;
+ const velocity = parseFloat(document.getElementById("velocity").value);
+ try {
+ if (action.startsWith("move-")) {
+ const distance = signedStep(chosenBar, action.slice("move-".length));
+ await api("POST", `/api/axes/${chosenBar}/move_relative`, { distance, velocity });
+ } else {
+ await api("POST", `/api/axes/${chosenBar}/${action}`, {});
+ }
+ showMessage("");
+ } catch (error) {
+ showError(`${chosenBar} ${action}: ${error.message}`);
+ }
+});
+
+function render(status) {
+ inControl = status.in_control;
+ document.getElementById("control-state").textContent = status.controller
+ ? (inControl ? "You are in control" : `${status.controller} is in control`)
+ : "Nobody is in control";
+ document.getElementById("take").hidden = inControl;
+ document.getElementById("password").hidden = inControl;
+ document.getElementById("release").hidden = !inControl;
+ if (status.error) showError(`PLC: ${status.error}`);
+ const plc = document.getElementById("plc-state");
+ plc.textContent = `PLC: ${status.plc ?? "–"}`;
+ plc.className = `chip ${status.plc === "run" ? "ok" : "bad"}`;
+ if (!document.querySelector(".bar")) {
+ buildCsu(status.axes);
+ drawSparklines(lastHistory);
+ }
+ axesByName = Object.fromEntries(status.axes.map((axis) => [axis.name, axis]));
+ for (const axis of status.axes) renderBar(axis);
+ renderPanel();
+}
+
+let shownPresets = "";
+
+function presetButton(label, title, onClick, className = "") {
+ const button = document.createElement("button");
+ button.textContent = label;
+ button.title = title;
+ button.className = className;
+ button.addEventListener("click", onClick);
+ return button;
+}
+
+function renderPresets(names) {
+ if (selected && !names.includes(selected.name)) selected = null;
+ const key = [...names, selected?.name, inControl].join("\u0000");
+ if (key !== shownPresets) {
+ shownPresets = key;
+ document.getElementById("preset-list").replaceChildren(...names.map((name) => {
+ const group = document.createElement("span");
+ group.className = "preset";
+ group.append(
+ presetButton(name, `Show "${name}" on the bars`, () => togglePreset(name),
+ selected?.name === name ? "selected" : "small"),
+ presetButton("Go", `Move every enabled bar to "${name}"`, () => recallPreset(name), "control"),
+ presetButton("✕", `Delete "${name}"`, () => deletePreset(name), "small control"),
+ );
+ return group;
+ }));
+ }
+ for (const button of document.querySelectorAll("#presets .control, #preset-save")) {
+ button.disabled = !inControl;
+ }
+}
+
+async function togglePreset(name) {
+ if (selected?.name === name) {
+ selected = null;
+ } else {
+ try {
+ selected = { name, bars: await api("GET", `/api/presets/${encodeURIComponent(name)}`) };
+ } catch (error) {
+ showError(error.message);
+ }
+ }
+ poll();
+}
+
+async function recallPreset(name) {
+ try {
+ const result = await api("POST", `/api/presets/${encodeURIComponent(name)}/recall`);
+ showNotice(result.skipped.length ? `${name}: left in place (disabled): ${result.skipped.join(", ")}` : "");
+ } catch (error) {
+ showError(error.message);
+ }
+}
+
+async function deletePreset(name) {
+ if (!confirm(`Delete save point "${name}"?`)) return;
+ try {
+ await api("DELETE", `/api/presets/${encodeURIComponent(name)}`);
+ poll();
+ } catch (error) {
+ showError(error.message);
+ }
+}
+
+document.getElementById("preset-save").addEventListener("click", async () => {
+ const field = document.getElementById("preset-name");
+ try {
+ await api("POST", "/api/presets", { name: field.value });
+ field.value = "";
+ showMessage("");
+ poll();
+ } catch (error) {
+ showError(error.message);
+ }
+});
+
+async function poll() {
+ try {
+ const status = await api("GET", "/api/status");
+ render(status);
+ renderPresets(status.presets);
+ } catch (error) {
+ showError(`status: ${error.message}`);
+ }
+}
+
+document.getElementById("take").addEventListener("click", async () => {
+ try {
+ const password = document.getElementById("password");
+ await api("POST", "/api/control", { password: password.value });
+ password.value = "";
+ poll();
+ } catch (error) {
+ showError(error.message);
+ }
+});
+document.getElementById("release").addEventListener("click", async () => {
+ await api("DELETE", "/api/control");
+ poll();
+});
+document.getElementById("stop-all").addEventListener("click", () =>
+ api("POST", "/api/stop").catch((error) => showError(error.message)));
+
+// Renew the lease well inside its lifetime while this page holds control
+setInterval(() => {
+ if (inControl) api("POST", "/api/control", {}).catch((error) => showError(error.message));
+}, (LEASE_S * 1000) / 3);
+
+// Reopen the webcam stream if it breaks, so a network hiccup does not leave a dead image
+const cameraImage = document.querySelector("#camera img");
+if (cameraImage) {
+ const streamUrl = cameraImage.src;
+ cameraImage.addEventListener("error", () => {
+ setTimeout(() => { cameraImage.src = `${streamUrl}?t=${Date.now()}`; }, 1000);
+ });
+}
+
+api("GET", "/api/layout").then((loaded) => { layout = loaded; }).catch((error) => showError(error.message))
+ .finally(() => { setInterval(poll, 500); poll(); });
diff --git a/src/csu_demo/templates/index.html b/src/csu_demo/templates/index.html
new file mode 100644
index 0000000..42b7f36
--- /dev/null
+++ b/src/csu_demo/templates/index.html
@@ -0,0 +1,65 @@
+
+
+
+
+LRIS2 CSU demo
+
+
+
+
+
+
+
+ {% if has_camera %}
+
+ {% endif %}
+
+
Click a bar to control it
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Save points
+
+
+
+
+
+
+
+ Drive board temperature
+
+ Motor current |I|
+
+
+
+
+
+
+
diff --git a/src/csu_demo/web.py b/src/csu_demo/web.py
new file mode 100644
index 0000000..c1f9d2e
--- /dev/null
+++ b/src/csu_demo/web.py
@@ -0,0 +1,166 @@
+"""Flask routes for the CSU demo page, its JSON API and the webcam stream."""
+
+from __future__ import annotations
+
+from collections.abc import Iterator
+from typing import Any, Final
+
+from cooethercat import AxisError
+from flask import Flask, Response, jsonify, render_template, request
+
+from .camera import SharedCamera
+from .control import LEASE_S, ControlError, Controller
+from .history import TelemetryHistory
+from .layout import Layout
+from .power import PowerError, PowerPanel
+
+TOKEN_COOKIE: Final = "csu_control"
+_BOUNDARY: Final = "frame"
+_NUMBER_PARAMS: Final = ("distance", "target", "velocity")
+
+
+def create_app( # pylint: disable=too-many-locals,too-many-statements,too-many-arguments
+ controller: Controller,
+ camera: SharedCamera | None,
+ layout: Layout,
+ *,
+ history: TelemetryHistory | None = None,
+ power: PowerPanel | None = None,
+ power_errors: tuple[type[Exception], ...] = (OSError,),
+) -> Flask:
+ """Build the demo app around an already started controller."""
+ app = Flask(__name__)
+ refusals: tuple[type[Exception], ...] = (ControlError, PowerError, *power_errors)
+
+ @app.get("/")
+ def index() -> str:
+ return render_template("index.html", has_camera=camera is not None, lease_s=LEASE_S,
+ has_power=power is not None)
+
+ @app.get("/api/layout")
+ def show_layout() -> Response:
+ return jsonify(
+ rows=layout.rows,
+ bars={bar_name: {"side": slot.side, "row": slot.row, "plus": slot.plus}
+ for bar_name, slot in layout.slots.items()},
+ )
+
+ @app.get("/api/status")
+ def status() -> Response:
+ return jsonify(controller.status(request.cookies.get(TOKEN_COOKIE)))
+
+ @app.post("/api/control")
+ def take_control() -> Response | tuple[Response, int]:
+ body = request.get_json(silent=True) or {}
+ holder = str(request.remote_addr or "unknown")
+ try:
+ token = controller.acquire(holder, request.cookies.get(TOKEN_COOKIE),
+ body.get("password"))
+ except ControlError as error:
+ return jsonify(error=str(error)), 409
+ response = jsonify(ok=True)
+ response.set_cookie(TOKEN_COOKIE, token, httponly=True, samesite="Strict")
+ return response
+
+ @app.delete("/api/control")
+ def release_control() -> Response:
+ controller.release(request.cookies.get(TOKEN_COOKIE))
+ response = jsonify(ok=True)
+ response.delete_cookie(TOKEN_COOKIE)
+ return response
+
+ @app.post("/api/axes//")
+ def command(name: str, action: str) -> Response | tuple[Response, int]:
+ try:
+ params = _numbers(request.get_json(silent=True) or {})
+ controller.command(request.cookies.get(TOKEN_COOKIE), name, action, **params)
+ except (ControlError, AxisError, KeyError, ValueError) as error:
+ return jsonify(error=str(error)), 400
+ return jsonify(ok=True)
+
+ @app.post("/api/presets")
+ def save_preset() -> Response | tuple[Response, int]:
+ name = str((request.get_json(silent=True) or {}).get("name", ""))
+ try:
+ controller.save_preset(request.cookies.get(TOKEN_COOKIE), name)
+ except ControlError as error:
+ return jsonify(error=str(error)), 400
+ return jsonify(ok=True)
+
+ @app.get("/api/presets/")
+ def show_preset(name: str) -> Response | tuple[Response, int]:
+ try:
+ return jsonify(controller.preset(name))
+ except ControlError as error:
+ return jsonify(error=str(error)), 404
+
+ @app.post("/api/presets//recall")
+ def recall_preset(name: str) -> Response | tuple[Response, int]:
+ try:
+ skipped = controller.recall_preset(request.cookies.get(TOKEN_COOKIE), name)
+ except ControlError as error:
+ return jsonify(error=str(error)), 400
+ return jsonify(ok=True, skipped=skipped)
+
+ @app.delete("/api/presets/")
+ def delete_preset(name: str) -> Response | tuple[Response, int]:
+ try:
+ controller.delete_preset(request.cookies.get(TOKEN_COOKIE), name)
+ except ControlError as error:
+ return jsonify(error=str(error)), 400
+ return jsonify(ok=True)
+
+ @app.get("/api/history")
+ def telemetry_history() -> Response:
+ return jsonify(history.all_series() if history is not None else {})
+
+ @app.get("/api/power")
+ def power_status() -> Response | tuple[Response, int]:
+ if power is None:
+ return jsonify(error="no PDU configured"), 404
+ return jsonify(power.status())
+
+ @app.post("/api/power/")
+ def switch_power(outlet: str) -> Response | tuple[Response, int]:
+ if power is None:
+ return jsonify(error="no PDU configured"), 404
+ on = bool((request.get_json(silent=True) or {}).get("on"))
+ try:
+ controller.require_control(request.cookies.get(TOKEN_COOKIE))
+ if not on and controller.any_enabled():
+ raise PowerError("disable every bar before switching the drives off")
+ power.switch(outlet, on)
+ except refusals as error:
+ return jsonify(error=str(error)), 400
+ return jsonify(ok=True)
+
+ @app.post("/api/stop")
+ def stop_all() -> Response | tuple[Response, int]:
+ try:
+ controller.stop_all()
+ except ControlError as error:
+ return jsonify(error=str(error)), 502
+ return jsonify(ok=True)
+
+ @app.get("/stream.mjpg")
+ def stream() -> Response | tuple[str, int]:
+ if camera is None:
+ return "no camera configured", 404
+ return Response(
+ _multipart(camera.frames()),
+ mimetype=f"multipart/x-mixed-replace; boundary={_BOUNDARY}",
+ )
+
+ return app
+
+
+def _numbers(body: dict[str, Any]) -> dict[str, float]:
+ return {key: float(body[key]) for key in _NUMBER_PARAMS if key in body}
+
+
+def _multipart(frames: Iterator[bytes]) -> Iterator[bytes]:
+ for frame in frames:
+ yield (
+ f"--{_BOUNDARY}\r\nContent-Type: image/jpeg\r\n"
+ f"Content-Length: {len(frame)}\r\n\r\n"
+ ).encode() + frame + b"\r\n"
diff --git a/src/daemon.py b/src/daemon.py
index f530b3e..aa711f3 100644
--- a/src/daemon.py
+++ b/src/daemon.py
@@ -1,6 +1,18 @@
""" LRIS2 daemon base class """
+import os
+
from libby.daemon import LibbyDaemon
+# The instrument broker. A daemon on another host names it in LRIS2_BROKER_HOST;
+# the broker lets the guest account in remotely (loopback_users = none)
+BROKER_HOST = "localhost"
+BROKER_HOST_ENV = "LRIS2_BROKER_HOST"
+
+
+def broker_url() -> str:
+ """Return the instrument broker URL."""
+ return f"amqp://{os.environ.get(BROKER_HOST_ENV) or BROKER_HOST}"
+
class Lris2Daemon(LibbyDaemon):
"""Instantiates the LRIS2 daemon base using LibbyDaemon.
@@ -9,4 +21,8 @@ class Lris2Daemon(LibbyDaemon):
its own discovery.
"""
transport = "rabbitmq"
- discovery_enabled = False
\ No newline at end of file
+ discovery_enabled = False
+
+ def config_rabbitmq_url(self) -> str:
+ """Return the configured URL if there is one, else the instrument broker."""
+ return self.rabbitmq_url or broker_url()
diff --git a/systemd/README.md b/systemd/README.md
index 3f1c034..770d105 100644
--- a/systemd/README.md
+++ b/systemd/README.md
@@ -44,6 +44,20 @@ sudo. It is safe to re-run and reports only what it changes.
Override `LRIS2_REPO_DIR`, `LRIS2_VENV_DIR` and `LRIS2_ETC_DIR` for other
paths.
+## Secrets
+
+Credentials and per-host settings live in `/etc/lris2/secrets.env`, which every
+unit reads at start; restart a service after changing it.
+
+| Variable | Host | Used by |
+|---|---|---|
+| `LRIS2_INFLUX_TOKEN` | lris2-137 | keygrabber |
+| `LRIS2_PDU_USERNAME` | lris2-137, lris2-ethercat | `l2power` daemons |
+| `LRIS2_PDU137_PASSWORD` | lris2-137 | `l2power_pdu_137`; the PDU's serial number |
+| `LRIS2_PDUETHERCAT_PASSWORD` | lris2-ethercat | `l2power_pdu_ethercat`; the PDU's serial number |
+| `LRIS2_BROKER_HOST` | lris2-ethercat | every daemon on a host without the broker |
+| `LRIS2_CSU_DEMO_PASSWORD` | lris2-ethercat | taking control in `lris2-csu-demo` |
+
## Day to day
Nothing below needs root, for anyone in `lris2-ops`:
@@ -79,6 +93,12 @@ sudo systemctl enable --now lris2-dashboard
ssh -L 8750:127.0.0.1:8750 # then open http://127.0.0.1:8750/
```
+## CSU demo
+
+`lris2-csu-demo.service` serves the CSU browser demo on port 8088 of the host
+installed with `--extra csu-demo`. Set `LRIS2_CSU_DEMO_PASSWORD` in
+[`secrets.env`](#secrets), then `sudo systemctl enable --now lris2-csu-demo`.
+
## Updating
```bash
diff --git a/systemd/install.sh b/systemd/install.sh
index 67a2b9a..69474a9 100755
--- a/systemd/install.sh
+++ b/systemd/install.sh
@@ -88,4 +88,11 @@ if ((${#EXTRAS[@]})); then
printf '%s\n' "${EXTRAS[@]}" >"$EXTRAS_FILE"
fi
+# The browser demo has its own unit, beside the lris2@ daemons
+if printf '%s\n' "${EXTRAS[@]}" | grep -qx csu-demo; then
+ install -m 644 "$REPO_DIR/systemd/lris2-csu-demo.service" /etc/systemd/system/
+ systemctl daemon-reload
+ echo "installed lris2-csu-demo.service; start it with: sudo systemctl enable --now lris2-csu-demo"
+fi
+
exec "$VENV_DIR/bin/lris2" install "${INSTALL_ARGS[@]}"
diff --git a/systemd/instances/csu.env b/systemd/instances/csu.env
new file mode 100644
index 0000000..ba51496
--- /dev/null
+++ b/systemd/instances/csu.env
@@ -0,0 +1,8 @@
+# csu: the CSU slit bars over ADS through the PLC
+#
+# lris2 deploy csu
+#
+# Deployed alongside this file by the CLI:
+# config//csu.yaml -> /etc/lris2/csu.yaml
+LRIS2_DAEMON=csu
+LRIS2_HOST=ethercat
diff --git a/systemd/instances/l2power_pdu1.env b/systemd/instances/l2power_pdu1.env
deleted file mode 100644
index 751a446..0000000
--- a/systemd/instances/l2power_pdu1.env
+++ /dev/null
@@ -1,8 +0,0 @@
-# l2power_pdu1: Eaton EMAT-08 PDU 1 (epduB2)
-#
-# lris2 deploy l2power_pdu1
-#
-# Deployed alongside this file by the CLI:
-# config//l2power_pdu1.yaml -> /etc/lris2/l2power_pdu1.yaml
-LRIS2_DAEMON=l2power/eaton_pdu
-LRIS2_HOST=lris2
diff --git a/systemd/instances/l2power_pdu_137.env b/systemd/instances/l2power_pdu_137.env
new file mode 100644
index 0000000..7147063
--- /dev/null
+++ b/systemd/instances/l2power_pdu_137.env
@@ -0,0 +1,8 @@
+# l2power_pdu_137: Eaton EMAT-08 PDU 1 (epduB2)
+#
+# lris2 deploy l2power_pdu_137
+#
+# Deployed alongside this file by the CLI:
+# config//l2power_pdu_137.yaml -> /etc/lris2/l2power_pdu_137.yaml
+LRIS2_DAEMON=l2power/eaton_pdu
+LRIS2_HOST=lris2
diff --git a/systemd/instances/l2power_pdu_ethercat.env b/systemd/instances/l2power_pdu_ethercat.env
new file mode 100644
index 0000000..c1a3be0
--- /dev/null
+++ b/systemd/instances/l2power_pdu_ethercat.env
@@ -0,0 +1,8 @@
+# l2power_pdu_ethercat: Eaton EMAT-08 PDU in the CSU lab (epduC5)
+#
+# lris2 deploy l2power_pdu_ethercat
+#
+# Deployed alongside this file by the CLI:
+# config//l2power_pdu_ethercat.yaml -> /etc/lris2/l2power_pdu_ethercat.yaml
+LRIS2_DAEMON=l2power/eaton_pdu
+LRIS2_HOST=ethercat
diff --git a/systemd/lris2-csu-demo.service b/systemd/lris2-csu-demo.service
new file mode 100644
index 0000000..9b32e2c
--- /dev/null
+++ b/systemd/lris2-csu-demo.service
@@ -0,0 +1,38 @@
+# Installed by install.sh on the host with --extra csu-demo.
+#
+# Serves the CSU browser demo on port 8088 of every interface. It drives the bars
+# only through lris2.csu, and taking control needs LRIS2_CSU_DEMO_PASSWORD.
+
+[Unit]
+Description=LRIS2 CSU browser demo
+After=network-online.target lris2@csu.service
+Wants=network-online.target
+
+[Service]
+Type=simple
+User=lris2
+Group=lris2
+# The webcam
+SupplementaryGroups=video
+# Broker host and the control password; systemd reads it as root
+EnvironmentFile=-/etc/lris2/secrets.env
+ExecStart=/opt/lris2/venv/bin/lris2-csu-demo --config /opt/lris2/app/config/csu/csu.yaml \
+ --layout /opt/lris2/app/config/csu/layout.yaml --host 0.0.0.0 --port 8088
+Environment=PYTHONUNBUFFERED=1
+# Save points live in /var/lib/lris2-csu-demo
+StateDirectory=lris2-csu-demo
+
+Restart=on-failure
+RestartSec=5
+
+StandardOutput=journal
+StandardError=journal
+SyslogIdentifier=lris2-csu-demo
+
+NoNewPrivileges=true
+ProtectSystem=strict
+ProtectHome=true
+PrivateTmp=true
+
+[Install]
+WantedBy=multi-user.target
diff --git a/tests/test_csu_demo.py b/tests/test_csu_demo.py
new file mode 100644
index 0000000..2bfc325
--- /dev/null
+++ b/tests/test_csu_demo.py
@@ -0,0 +1,394 @@
+"""Tests for the CSU browser demo against simulated axes and a fake camera."""
+
+from __future__ import annotations
+
+import threading
+import time
+from collections.abc import Iterator
+from pathlib import Path
+from typing import Any, ClassVar
+
+import pytest
+from cooethercat import AxisSet
+from cooethercat.backends.sim import open_simulated
+from cooethercat.config import parse_topology
+from flask.testing import FlaskClient
+from lris2.csu_demo.camera import SharedCamera
+from lris2.csu_demo.control import LEASE_S, Controller
+from lris2.csu_demo.layout import Layout, LayoutError, Side, Slot, load_layout
+from lris2.csu_demo.presets import PresetStore, SavedBar
+from lris2.csu_demo.web import TOKEN_COOKIE, create_app
+
+TOPOLOGY: dict[str, Any] = {
+ "name": "csu-sim",
+ "backend": "sim",
+ "transport": {"tick_s": 0.002},
+ "defaults": {
+ "units": {"name": "mm"},
+ "limits": {"velocity": 50.0, "min_position": -20.0, "max_position": 20.0},
+ },
+ "axes": [{"name": "CSU-0"}, {"name": "CSU-1"}],
+}
+JPEG = b"\xff\xd8fake-frame\xff\xd9"
+LAYOUT = Layout(rows=12, slots={"CSU-0": Slot(Side.LEFT, 7, Side.LEFT)})
+REPO_LAYOUT = Path(__file__).parent.parent / "config" / "csu" / "layout.yaml"
+
+
+class FakeSource:
+ """Endless stream of identical JPEG frames."""
+
+ instances: ClassVar[list[FakeSource]] = []
+
+ def __init__(self) -> None:
+ self.closed = threading.Event()
+ FakeSource.instances.append(self)
+
+ def read(self, size: int) -> bytes:
+ if self.closed.wait(0.01):
+ return b""
+ return JPEG
+
+ def close(self) -> None:
+ self.closed.set()
+
+
+class FakeClock:
+ """Manually advanced monotonic clock."""
+
+ def __init__(self) -> None:
+ self.now = 0.0
+
+ def __call__(self) -> float:
+ return self.now
+
+
+@pytest.fixture(name="clock")
+def clock_fixture() -> FakeClock:
+ return FakeClock()
+
+
+@pytest.fixture(name="presets_path")
+def presets_path_fixture(tmp_path: Path) -> Path:
+ return tmp_path / "presets.json"
+
+
+@pytest.fixture(name="axes")
+def axes_fixture() -> Iterator[AxisSet]:
+ with open_simulated(parse_topology(TOPOLOGY)) as axes:
+ yield axes
+
+
+@pytest.fixture(name="controller")
+def controller_fixture(axes: AxisSet, clock: FakeClock, presets_path: Path) -> Controller:
+ controller = Controller(axes, PresetStore(presets_path), clock=clock)
+ controller.refresh()
+ return controller
+
+
+@pytest.fixture(name="camera")
+def camera_fixture() -> SharedCamera:
+ FakeSource.instances.clear()
+ return SharedCamera(FakeSource)
+
+
+@pytest.fixture(name="client")
+def client_fixture(controller: Controller, camera: SharedCamera) -> FlaskClient:
+ return create_app(controller, camera, LAYOUT).test_client()
+
+
+def _take_control(client: FlaskClient) -> None:
+ assert client.post("/api/control", json={}).status_code == 200
+
+
+def _position(client: FlaskClient, controller: Controller, name: str) -> float:
+ controller.refresh()
+ axes = client.get("/api/status").get_json()["axes"]
+ return float(next(axis["position"] for axis in axes if axis["name"] == name))
+
+
+def _wait_for(predicate: Any, timeout_s: float = 2.0) -> None:
+ deadline = time.monotonic() + timeout_s
+ while not predicate():
+ assert time.monotonic() < deadline, "condition not reached"
+ time.sleep(0.01)
+
+
+def test_index_serves_page_with_stream(client: FlaskClient) -> None:
+ page = client.get("/").get_data(as_text=True)
+ assert "stream.mjpg" in page
+
+
+def test_status_lists_every_axis(client: FlaskClient) -> None:
+ status = client.get("/api/status").get_json()
+ assert [axis["name"] for axis in status["axes"]] == ["CSU-0", "CSU-1"]
+ assert status["axes"][0]["units"] == "mm"
+ assert status["controller"] is None
+
+
+def test_commands_need_control(client: FlaskClient) -> None:
+ response = client.post("/api/axes/CSU-0/enable", json={})
+ assert response.status_code == 400
+ assert "take control" in response.get_json()["error"]
+
+
+def test_operator_enables_and_moves(client: FlaskClient, controller: Controller) -> None:
+ _take_control(client)
+ assert client.post("/api/axes/CSU-0/enable", json={}).status_code == 200
+ response = client.post("/api/axes/CSU-0/move_relative", json={"distance": 5, "velocity": 40})
+ assert response.status_code == 200
+
+ def landed() -> bool:
+ controller.refresh()
+ axis = client.get("/api/status").get_json()["axes"][0]
+ return not axis["moving"] and axis["position"] == pytest.approx(5.0)
+
+ _wait_for(landed)
+
+
+def test_move_outside_travel_is_refused(client: FlaskClient) -> None:
+ _take_control(client)
+ client.post("/api/axes/CSU-0/enable", json={})
+ response = client.post("/api/axes/CSU-0/move_relative", json={"distance": 30, "velocity": 5})
+ assert response.status_code == 400
+ assert "travel" in response.get_json()["error"]
+
+
+def test_second_operator_is_refused_until_lease_expires(
+ client: FlaskClient, controller: Controller, clock: FakeClock
+) -> None:
+ _take_control(client)
+ other = create_app(controller, None, LAYOUT).test_client()
+ other.environ_base["REMOTE_ADDR"] = "10.1.1.20"
+ assert other.post("/api/control", json={}).status_code == 409
+ clock.now += LEASE_S + 1
+ assert other.post("/api/control", json={}).status_code == 200
+ assert other.get("/api/status").get_json()["controller"] == "10.1.1.20"
+
+
+def test_holder_is_shown_by_address(client: FlaskClient) -> None:
+ _take_control(client)
+ assert client.post("/api/control", json={}).status_code == 200
+ assert client.get("/api/status").get_json()["controller"] == "127.0.0.1"
+
+
+def test_release_clears_control(client: FlaskClient) -> None:
+ _take_control(client)
+ client.delete("/api/control")
+ status = client.get("/api/status").get_json()
+ assert status["controller"] is None
+ assert client.get_cookie(TOKEN_COOKIE) is None
+
+
+def test_plc_error_during_command_is_reported_as_json(
+ client: FlaskClient, controller: Controller, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _take_control(client)
+
+ def broken_link(*_: Any) -> None:
+ raise OSError("ADS link lost")
+
+ monkeypatch.setattr(controller, "_run", broken_link)
+ response = client.post("/api/axes/CSU-0/enable", json={})
+ assert response.status_code == 400
+ assert "ADS link lost" in response.get_json()["error"]
+
+
+def test_save_point_round_trip(client: FlaskClient, controller: Controller) -> None:
+ _take_control(client)
+ for bar in ("CSU-0", "CSU-1"):
+ client.post(f"/api/axes/{bar}/enable", json={})
+ client.post("/api/axes/CSU-0/move_relative", json={"distance": 4, "velocity": 40})
+ _wait_for(lambda: _position(client, controller, "CSU-0") == pytest.approx(4.0))
+
+ assert client.post("/api/presets", json={"name": "open"}).status_code == 200
+ assert client.get("/api/status").get_json()["presets"] == ["open"]
+
+ client.post("/api/axes/CSU-0/move_relative", json={"distance": -9, "velocity": 40})
+ client.post("/api/axes/CSU-1/move_relative", json={"distance": 6, "velocity": 40})
+ _wait_for(lambda: _position(client, controller, "CSU-1") == pytest.approx(6.0))
+
+ response = client.post("/api/presets/open/recall")
+ assert response.get_json() == {"ok": True, "skipped": []}
+ _wait_for(lambda: _position(client, controller, "CSU-0") == pytest.approx(4.0)
+ and _position(client, controller, "CSU-1") == pytest.approx(0.0))
+
+
+def test_recall_skips_disabled_bars(client: FlaskClient, controller: Controller) -> None:
+ _take_control(client)
+ client.post("/api/presets", json={"name": "home"})
+ client.post("/api/axes/CSU-1/enable", json={})
+ response = client.post("/api/presets/home/recall")
+ assert response.get_json()["skipped"] == ["CSU-0"]
+
+
+def test_recall_out_of_travel_moves_nothing(axes: AxisSet, tmp_path: Path) -> None:
+ stored = tmp_path / "hand-edited.json"
+ stored.write_text('{"bad": {"CSU-0": 1.0, "CSU-1": 99.0}}')
+ controller = Controller(axes, PresetStore(stored))
+ client = create_app(controller, None, LAYOUT).test_client()
+ _take_control(client)
+ for bar in ("CSU-0", "CSU-1"):
+ client.post(f"/api/axes/{bar}/enable", json={})
+ response = client.post("/api/presets/bad/recall")
+ assert response.status_code == 400
+ assert "CSU-1" in response.get_json()["error"]
+ time.sleep(0.05)
+ assert _position(client, controller, "CSU-0") == pytest.approx(0.0)
+
+
+def test_save_points_survive_a_restart(presets_path: Path) -> None:
+ PresetStore(presets_path).save("near center", {"CSU-0": SavedBar(1.5, enabled=True)})
+ reopened = PresetStore(presets_path)
+ assert reopened.names() == ["near center"]
+ assert reopened.get("near center")["CSU-0"] == SavedBar(1.5, enabled=True)
+
+
+def test_save_points_without_enabled_state_still_load(presets_path: Path) -> None:
+ presets_path.write_text('{"StatusQuo": {"CSU-0": -437.052}}')
+ assert PresetStore(presets_path).get("StatusQuo")["CSU-0"] == SavedBar(-437.052)
+
+
+def test_save_point_records_enabled_states(client: FlaskClient) -> None:
+ _take_control(client)
+ client.post("/api/axes/CSU-1/enable", json={})
+ client.post("/api/presets", json={"name": "working"})
+ saved = client.get("/api/presets/working").get_json()
+ assert saved["CSU-0"] == {"position": 0.0, "enabled": False}
+ assert saved["CSU-1"] == {"position": 0.0, "enabled": True}
+
+
+def test_viewing_a_save_point_needs_no_control(client: FlaskClient) -> None:
+ _take_control(client)
+ client.post("/api/presets", json={"name": "open"})
+ client.delete("/api/control")
+ assert client.get("/api/presets/open").status_code == 200
+ assert client.get("/api/presets/missing").status_code == 404
+
+
+def test_save_points_need_control(client: FlaskClient) -> None:
+ assert client.post("/api/presets", json={"name": "x"}).status_code == 400
+ assert client.post("/api/presets/x/recall").status_code == 400
+
+
+def test_delete_save_point(client: FlaskClient) -> None:
+ _take_control(client)
+ client.post("/api/presets", json={"name": "tmp"})
+ assert client.delete("/api/presets/tmp").status_code == 200
+ assert client.get("/api/status").get_json()["presets"] == []
+ assert client.delete("/api/presets/tmp").status_code == 400
+
+
+def test_poll_error_reopens_the_transport(
+ controller: Controller, axes: AxisSet, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ calls: list[str] = []
+
+ def lost_link() -> dict[str, Any]:
+ raise OSError("Broken pipe")
+
+ monkeypatch.setattr(next(iter(axes)), "status", lost_link)
+ monkeypatch.setattr(axes.backend, "close", lambda: calls.append("close"))
+ monkeypatch.setattr(axes.backend, "open", lambda: calls.append("open"))
+ controller.refresh()
+ assert calls == ["close", "open"]
+ assert "Broken pipe" in controller.status(None)["error"]
+
+
+def test_stop_all_needs_no_control(client: FlaskClient) -> None:
+ assert client.post("/api/stop").status_code == 200
+
+
+def test_stop_all_continues_past_a_failed_axis(
+ client: FlaskClient, controller: Controller, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ stopped = []
+
+ def stop(axis: Any) -> None:
+ if axis.name == "CSU-0":
+ raise OSError("ADS link lost")
+ stopped.append(axis.name)
+
+ monkeypatch.setattr("cooethercat.axis.Axis.stop", stop)
+ response = client.post("/api/stop")
+ assert response.status_code == 502
+ assert "CSU-0" in response.get_json()["error"]
+ assert stopped == ["CSU-1"]
+
+
+def test_controller_stop_disables_axes(controller: Controller) -> None:
+ token = controller.acquire("alice", None)
+ controller.command(token, "CSU-0", "enable")
+
+ def all_disabled() -> bool:
+ controller.refresh()
+ return not any(axis["enabled"] for axis in controller.status(None)["axes"])
+
+ controller.stop()
+ _wait_for(all_disabled)
+
+
+def test_camera_runs_only_while_watched(camera: SharedCamera) -> None:
+ frames = camera.frames()
+ assert next(frames) == JPEG
+ assert camera.running and camera.viewers == 1
+ frames.close()
+ assert not camera.running and camera.viewers == 0
+ assert FakeSource.instances[0].closed.is_set()
+
+
+def test_camera_shares_one_capture(camera: SharedCamera) -> None:
+ first, second = camera.frames(), camera.frames()
+ assert next(first) == JPEG and next(second) == JPEG
+ assert len(FakeSource.instances) == 1
+ first.close()
+ assert camera.running
+ second.close()
+ assert not camera.running
+
+
+def test_camera_restarts_for_a_later_viewer(camera: SharedCamera) -> None:
+ first = camera.frames()
+ assert next(first) == JPEG
+ first.close()
+ second = camera.frames()
+ assert next(second) == JPEG
+ second.close()
+ assert len(FakeSource.instances) == 2
+
+
+def test_stream_is_multipart_jpeg(client: FlaskClient) -> None:
+ response = client.get("/stream.mjpg", buffered=False)
+ assert response.mimetype == "multipart/x-mixed-replace"
+ chunk = next(iter(response.response))
+ assert chunk.startswith(b"--frame\r\nContent-Type: image/jpeg") and JPEG in chunk
+ response.close()
+
+
+def test_layout_endpoint_lists_placed_bars(client: FlaskClient) -> None:
+ layout = client.get("/api/layout").get_json()
+ assert layout == {"rows": 12, "bars": {"CSU-0": {"side": "left", "row": 7, "plus": "left"}}}
+
+
+def test_repo_layout_loads() -> None:
+ layout = load_layout(REPO_LAYOUT)
+ assert layout.slot("CSU-6") == Slot(Side.LEFT, 5, Side.RIGHT)
+ assert layout.slot("CSU-18") == Slot(Side.RIGHT, 5, Side.RIGHT)
+ assert layout.slot("CSU-10") == Slot(Side.LEFT, 1, Side.RIGHT)
+ assert layout.slot("CSU-11") is None
+
+
+@pytest.mark.parametrize(
+ ("bars", "message"),
+ [
+ ("{CSU-0: {side: left, row: 1, plus: left}, CSU-1: {side: left, row: 1, plus: left}}",
+ "both sit left row 1"),
+ ("{CSU-0: {side: left, row: 13, plus: left}}", "outside 1..12"),
+ ("{CSU-0: {side: up, row: 1, plus: left}}", "up"),
+ ("{CSU-0: {side: left, row: 1, plus: left, colour: red}}", "unknown keys"),
+ ],
+)
+def test_layout_rejects_ambiguous_files(tmp_path: Path, bars: str, message: str) -> None:
+ path = tmp_path / "layout.yaml"
+ path.write_text(f"rows: 12\nbars: {bars}\n")
+ with pytest.raises(LayoutError, match=message):
+ load_layout(path)
diff --git a/tests/test_csu_demo_libby.py b/tests/test_csu_demo_libby.py
new file mode 100644
index 0000000..07161dd
--- /dev/null
+++ b/tests/test_csu_demo_libby.py
@@ -0,0 +1,219 @@
+"""The demo's libby backend, driven against the CSU daemon's keywords on simulated bars."""
+
+from __future__ import annotations
+
+import time
+from collections.abc import Callable, Iterator
+from typing import Any
+
+import pytest
+from cooethercat import Axis, AxisError, AxisSet, ControllerState
+from cooethercat.backends.sim import open_simulated
+from cooethercat.config import parse_topology
+from libby.keyword import Keyword
+from libby.keyword_registry import KeywordRegistry
+from lris2.csu.keywords import CsuKeywords
+from lris2.csu_demo.control import ControlError, Controller
+from lris2.csu_demo.history import TelemetryHistory, record_telemetry
+from lris2.csu_demo.layout import Layout
+from lris2.csu_demo.libby_backend import LibbyBackend
+from lris2.csu_demo.power import OUTLETS, PowerPanel
+from lris2.csu_demo.presets import PresetStore
+from lris2.csu_demo.web import create_app
+
+TOPOLOGY: dict[str, Any] = {
+ "name": "csu-sim",
+ "backend": "sim",
+ "transport": {"tick_s": 0.002},
+ "defaults": {
+ "units": {"name": "mm"},
+ "limits": {"velocity": 50.0, "min_position": -20.0, "max_position": 20.0},
+ },
+ "axes": [{"name": "CSU-0"}, {"name": "CSU-6"}],
+}
+
+
+class DaemonClient:
+ """Answer libby gets and sets from the CSU keywords, as the daemon would."""
+
+ def __init__(self, keywords: dict[str, Keyword]) -> None:
+ self.keywords = keywords
+ self.status_reads = 0
+
+ def get(self, name: str, *, timeout_s: float = 2.0) -> Any:
+ keyword = name.removeprefix("lris2.csu.")
+ self.status_reads += keyword == "status"
+ if keyword == "plcstate":
+ return "run"
+ return self._reply(self.keywords[keyword].handle({}))
+
+ def set(self, name: str, value: Any, *, timeout_s: float | None = None) -> Any:
+ return self._reply(self.keywords[name.removeprefix("lris2.csu.")].handle({"value": value}))
+
+ @staticmethod
+ def _reply(reply: dict[str, Any]) -> Any:
+ if reply.get("ok", True) is False:
+ raise RuntimeError(reply.get("error", "keyword failed"))
+ return reply.get("value")
+
+
+@pytest.fixture(name="daemon_axes")
+def daemon_axes_fixture() -> Iterator[AxisSet]:
+ with open_simulated(parse_topology(TOPOLOGY)) as axes:
+ yield axes
+
+
+@pytest.fixture(name="client")
+def client_fixture(daemon_axes: AxisSet) -> DaemonClient:
+ registry = KeywordRegistry()
+ CsuKeywords(daemon_axes).register(registry)
+ return DaemonClient({keyword.name: keyword for keyword in registry.drain()})
+
+
+@pytest.fixture(name="axes")
+def axes_fixture(client: DaemonClient) -> AxisSet:
+ backend = LibbyBackend(client)
+ topology = parse_topology(TOPOLOGY)
+ axes = AxisSet(backend, {config.keyword_name: Axis(backend, config) for config in topology.axes})
+ backend.open()
+ return axes
+
+
+def wait_for(predicate: Callable[[], bool], timeout_s: float = 2.0) -> None:
+ deadline = time.monotonic() + timeout_s
+ while not predicate():
+ assert time.monotonic() < deadline, "condition not reached"
+ time.sleep(0.01)
+
+
+def test_enable_and_relative_move(axes: AxisSet, daemon_axes: AxisSet) -> None:
+ bar = axes.axis("CSU-6")
+ bar.enable()
+ bar.move_relative(4.0, velocity=40.0, wait=False)
+ wait_for(lambda: daemon_axes.axis("CSU-6").position == pytest.approx(4.0))
+ bar.move_relative(-1.5, velocity=40.0, wait=False)
+ wait_for(lambda: daemon_axes.axis("CSU-6").position == pytest.approx(2.5))
+
+
+def test_absolute_move_and_halt(axes: AxisSet, daemon_axes: AxisSet) -> None:
+ bar = axes.axis("CSU-0")
+ bar.enable()
+ bar.move_absolute(15.0, velocity=1.0, wait=False)
+ wait_for(lambda: daemon_axes.axis("CSU-0").moving)
+ bar.stop()
+ wait_for(lambda: not daemon_axes.axis("CSU-0").moving)
+ assert daemon_axes.axis("CSU-0").position < 15.0
+
+
+def test_one_status_read_serves_every_bar(axes: AxisSet, client: DaemonClient) -> None:
+ for bar in axes:
+ bar.status()
+ assert client.status_reads == 1
+
+
+def test_disabled_bar_refuses_to_move(axes: AxisSet) -> None:
+ with pytest.raises(AxisError):
+ axes.axis("CSU-0").move_relative(1.0, wait=False)
+
+
+def test_controller_state_comes_from_the_daemon(axes: AxisSet) -> None:
+ assert axes.backend.controller_state() is ControllerState.RUN
+
+
+def test_taking_control_needs_the_password(axes: AxisSet, tmp_path: Any) -> None:
+ controller = Controller(axes, PresetStore(tmp_path / "presets.json"), password="s3cret")
+ with pytest.raises(ControlError, match="wrong password"):
+ controller.acquire("mallory", None, "guess")
+ token = controller.acquire("alice", None, "s3cret")
+ assert controller.acquire("alice", token) == token
+
+
+class FakePdu:
+ """The CSU lab PDU's outlet keywords."""
+
+ def __init__(self) -> None:
+ self.values: dict[str, Any] = {}
+ for name, _ in OUTLETS:
+ self.values |= {f"state_{name}": True, f"power_{name}": 10.0, f"current_{name}": 0.1}
+
+ def get(self, name: str, *, timeout_s: float = 2.0) -> Any:
+ return self.values[name.removeprefix("l2power.pdu-ethercat.")]
+
+ def set(self, name: str, value: Any, *, timeout_s: float | None = None) -> Any:
+ self.values[name.removeprefix("l2power.pdu-ethercat.")] = value
+ return value
+
+
+def test_history_trims_to_its_window() -> None:
+ history = TelemetryHistory(window_s=100.0)
+ history.add(0.0, {"CSU-6": {"boardtemp": 60.0, "current": 0.0}})
+ history.add(50.0, {"CSU-6": {"boardtemp": 61.0, "current": None}})
+ history.add(150.0, {"CSU-6": {"boardtemp": 62.0, "current": 5.0}})
+ assert history.series("CSU-6") == {"time": [50.0, 150.0], "boardtemp": [61.0, 62.0],
+ "current": [None, 5.0]}
+ assert history.series("CSU-0") == {"time": []}
+
+
+def test_telemetry_poll_records_the_daemon_reading(client: DaemonClient) -> None:
+ history = TelemetryHistory()
+ record_telemetry(lambda: client.get("lris2.csu.telemetry"), history, clock=lambda: 1.0)()
+ assert history.series("CSU-6")["time"] == [1.0]
+
+
+@pytest.fixture(name="web")
+def web_fixture(axes: AxisSet, tmp_path: Any) -> tuple[Any, FakePdu, Controller]:
+ pdu = FakePdu()
+ controller = Controller(axes, PresetStore(tmp_path / "presets.json"))
+ controller.refresh()
+ panel = PowerPanel(pdu)
+ panel.refresh()
+ app = create_app(controller, None, Layout(rows=12, slots={}), history=TelemetryHistory(),
+ power=panel)
+ return app.test_client(), pdu, controller
+
+
+def test_power_status_lists_every_outlet(web: tuple[Any, FakePdu, Controller]) -> None:
+ flask_client, _, _ = web
+ outlets = flask_client.get("/api/power").get_json()["outlets"]
+ assert [outlet["name"] for outlet in outlets] == [name for name, _ in OUTLETS]
+ assert [outlet["name"] for outlet in outlets if outlet["switchable"]] == ["ethercat"]
+
+
+def test_drives_switch_needs_control_and_no_bar_enabled(
+ web: tuple[Any, FakePdu, Controller], axes: AxisSet
+) -> None:
+ flask_client, pdu, controller = web
+ assert flask_client.post("/api/power/ethercat", json={"on": False}).status_code == 400
+ assert flask_client.post("/api/control", json={}).status_code == 200
+ axes.axis("CSU-0").enable()
+ controller.refresh()
+ refused = flask_client.post("/api/power/ethercat", json={"on": False})
+ assert "disable every bar" in refused.get_json()["error"]
+ axes.axis("CSU-0").disable()
+ controller.refresh()
+ assert flask_client.post("/api/power/ethercat", json={"on": False}).status_code == 200
+ assert pdu.values["state_ethercat"] is False
+
+
+def test_only_the_drives_outlet_switches(web: tuple[Any, FakePdu, Controller]) -> None:
+ flask_client, pdu, _ = web
+ flask_client.post("/api/control", json={})
+ assert flask_client.post("/api/power/plc", json={"on": False}).status_code == 400
+ assert pdu.values["state_plc"] is True
+
+
+def test_history_route_serves_every_bar(web: tuple[Any, FakePdu, Controller]) -> None:
+ flask_client, _, _ = web
+ assert flask_client.get("/api/history").get_json() == {}
+
+
+def test_all_series_keys_by_bar() -> None:
+ history = TelemetryHistory()
+ history.add(1.0, {"CSU-0": {"current": 3.0}, "CSU-6": {"current": 4.0}})
+ assert history.all_series()["CSU-6"] == {"time": [1.0], "current": [4.0]}
+
+
+def test_status_reports_the_plc_mode(axes: AxisSet, tmp_path: Any) -> None:
+ controller = Controller(axes, PresetStore(tmp_path / "presets.json"))
+ controller.refresh()
+ assert controller.status(None)["plc"] == "run"
diff --git a/tests/test_csu_keywords.py b/tests/test_csu_keywords.py
new file mode 100644
index 0000000..3e36374
--- /dev/null
+++ b/tests/test_csu_keywords.py
@@ -0,0 +1,139 @@
+"""CSU keywords exercised through libby's registry against simulated bars."""
+
+from __future__ import annotations
+
+import json
+import time
+from collections.abc import Callable, Iterator
+from typing import Any
+
+import pytest
+from cooethercat import AxisSet
+from cooethercat.backends.sim import SimBackend, open_simulated
+from cooethercat.config import parse_topology
+from libby.keyword import Keyword
+from libby.keyword_registry import KeywordRegistry
+from lris2.csu.keywords import TELEMETRY, CsuKeywords
+
+TOPOLOGY: dict[str, Any] = {
+ "name": "csu-sim",
+ "backend": "sim",
+ "transport": {"tick_s": 0.002},
+ "defaults": {
+ "units": {"name": "mm"},
+ "limits": {"velocity": 50.0, "min_position": -20.0, "max_position": 20.0},
+ },
+ "axes": [{"name": "CSU-0"}, {"name": "CSU-6"}],
+}
+
+
+@pytest.fixture(name="axes")
+def axes_fixture() -> Iterator[AxisSet]:
+ with open_simulated(parse_topology(TOPOLOGY)) as axes:
+ yield axes
+
+
+@pytest.fixture(name="keywords")
+def keywords_fixture(axes: AxisSet) -> dict[str, Keyword]:
+ registry = KeywordRegistry()
+ CsuKeywords(axes).register(registry)
+ return {keyword.name: keyword for keyword in registry.drain()}
+
+
+def read(keywords: dict[str, Keyword], name: str) -> Any:
+ reply = keywords[name].handle({})
+ assert reply.get("ok", True), reply
+ return reply["value"]
+
+
+def fire(keywords: dict[str, Keyword], name: str) -> None:
+ reply = keywords[name].handle({"value": True})
+ assert reply.get("ok", True), reply
+
+
+def wait_for(predicate: Callable[[], bool], timeout_s: float = 2.0) -> None:
+ deadline = time.monotonic() + timeout_s
+ while not predicate():
+ assert time.monotonic() < deadline, "condition not reached"
+ time.sleep(0.01)
+
+
+def test_every_bar_gets_its_keywords(keywords: dict[str, Keyword]) -> None:
+ per_bar = {"positionvalue", "velocity", "ismoving", "isenabled", "error", "halt", "reset",
+ *(item.keyword for item in TELEMETRY)}
+ expected = {f"{name}{n}" for name in per_bar for n in (0, 6)} | {"ismoving", "halt", "status", "telemetry"}
+ assert set(keywords) == expected
+
+
+def test_enable_and_move_through_keywords(keywords: dict[str, Keyword]) -> None:
+ assert read(keywords, "isenabled6") is False
+ keywords["isenabled6"].handle({"value": True})
+ assert read(keywords, "isenabled6") is True
+ keywords["velocity6"].handle({"value": 40.0})
+ keywords["positionvalue6"].handle({"value": 7.5})
+ wait_for(lambda: read(keywords, "positionvalue6") == pytest.approx(7.5))
+ assert read(keywords, "ismoving") is False
+
+
+def test_move_without_velocity_uses_the_limit(axes: AxisSet, keywords: dict[str, Keyword]) -> None:
+ keywords["isenabled0"].handle({"value": True})
+ axes.axis("CSU-0").set("velocity", 0.0)
+ keywords["positionvalue0"].handle({"value": 3.0})
+ wait_for(lambda: read(keywords, "positionvalue0") == pytest.approx(3.0))
+
+
+def test_move_outside_travel_is_an_error_reply(keywords: dict[str, Keyword]) -> None:
+ keywords["isenabled0"].handle({"value": True})
+ reply = keywords["positionvalue0"].handle({"value": 99.0})
+ assert reply.get("ok") is False
+ assert read(keywords, "positionvalue0") == pytest.approx(0.0)
+
+
+def test_velocity_above_limit_is_refused(keywords: dict[str, Keyword]) -> None:
+ assert keywords["velocity0"].handle({"value": 500.0}).get("ok") is False
+
+
+def test_halt_stops_a_moving_bar(keywords: dict[str, Keyword]) -> None:
+ keywords["isenabled6"].handle({"value": True})
+ keywords["velocity6"].handle({"value": 1.0})
+ keywords["positionvalue6"].handle({"value": 15.0})
+ wait_for(lambda: read(keywords, "ismoving6"))
+ fire(keywords, "halt")
+ wait_for(lambda: not read(keywords, "ismoving6"))
+ assert read(keywords, "positionvalue6") < 15.0
+
+
+def test_fault_is_reported_and_reset(axes: AxisSet, keywords: dict[str, Keyword]) -> None:
+ backend = axes.backend
+ assert isinstance(backend, SimBackend)
+ backend.inject_fault("CSU-0", error_id=0x4650)
+ assert read(keywords, "error0") == 0x4650
+ fire(keywords, "reset0")
+ assert read(keywords, "error0") == 0
+
+
+def test_telemetry_is_scaled(axes: AxisSet, keywords: dict[str, Keyword]) -> None:
+ backend = axes.backend
+ assert isinstance(backend, SimBackend)
+ backend.set_object("CSU-6", 0x3201, 1, 724)
+ backend.set_object("CSU-6", 0x2200, 1, 233)
+ assert read(keywords, "boardtemp6") == pytest.approx(72.4)
+ assert read(keywords, "supply6") == pytest.approx(23.3)
+
+
+def test_status_covers_every_bar(keywords: dict[str, Keyword]) -> None:
+ keywords["isenabled6"].handle({"value": True})
+ status = json.loads(read(keywords, "status"))
+ assert set(status) == {"CSU-0", "CSU-6"}
+ assert status["CSU-6"]["enabled"] is True
+ assert status["CSU-0"]["position"] == pytest.approx(0.0)
+
+
+def test_telemetry_reads_every_bar(axes: AxisSet, keywords: dict[str, Keyword]) -> None:
+ backend = axes.backend
+ assert isinstance(backend, SimBackend)
+ backend.set_object("CSU-6", 0x3201, 1, 712)
+ backend.set_object("CSU-6", 0x30D1, 1, 150)
+ readings = json.loads(read(keywords, "telemetry"))
+ assert readings["CSU-6"] == {"boardtemp": pytest.approx(71.2), "current": pytest.approx(150.0)}
+ assert set(readings) == {"CSU-0", "CSU-6"}
diff --git a/tests/test_daemon_broker.py b/tests/test_daemon_broker.py
new file mode 100644
index 0000000..f9f245c
--- /dev/null
+++ b/tests/test_daemon_broker.py
@@ -0,0 +1,25 @@
+"""Broker URL selection for LRIS2 daemons."""
+
+import pytest
+from lris2 import daemon
+
+
+@pytest.fixture(autouse=True)
+def clean_environment(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv(daemon.BROKER_HOST_ENV, raising=False)
+
+
+def test_local_broker_by_default() -> None:
+ assert daemon.broker_url() == "amqp://localhost"
+
+
+def test_host_from_environment(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv(daemon.BROKER_HOST_ENV, "lris2-137")
+ assert daemon.broker_url() == "amqp://lris2-137"
+
+
+def test_configured_url_wins(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv(daemon.BROKER_HOST_ENV, "lris2-137")
+ instance = daemon.Lris2Daemon()
+ instance.rabbitmq_url = "amqp://elsewhere"
+ assert instance.config_rabbitmq_url() == "amqp://elsewhere"