Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 30 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/`.
Expand Down
15 changes: 13 additions & 2 deletions config/common/keygrabber.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
53 changes: 53 additions & 0 deletions config/csu/csu.yaml
Original file line number Diff line number Diff line change
@@ -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
21 changes: 21 additions & 0 deletions config/csu/layout.yaml
Original file line number Diff line number Diff line change
@@ -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}
Original file line number Diff line number Diff line change
@@ -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:
Expand All @@ -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
28 changes: 28 additions & 0 deletions config/l2power/l2power_pdu_ethercat.yaml
Original file line number Diff line number Diff line change
@@ -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
131 changes: 131 additions & 0 deletions daemons/csu
Original file line number Diff line number Diff line change
@@ -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())
2 changes: 1 addition & 1 deletion daemons/l2power/pdu_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
Loading
Loading